I am trying to run this small python script which inserts data to mySql database under MacOs however it gives me following error:
File "inserter.py", line 58, in cursor.execute('SELECT countryId from searcher_country');
File "build/bdist.macosx-10.9-intel/egg/MySQLdb/cursors.py", line 205, in execute
File "build/bdist.macosx-10.9-intel/egg/MySQLdb/connections.py", line 36, in defaulterrorhandler _mysql_exceptions.ProgrammingError: (2014, "Commands out of sync; you can't run this command now")
Script :
from openpyxl import load_workbook;
import MySQLdb;
import random;
connection = MySQLdb.connect(host='localhost',user='root',passwd='testpassword',db='test');
cursor = connection.cursor();
fileLoc = "data.xlsx";
wb = load_workbook(fileLoc);
ws = wb.active;
#outFile = raw_input("Where do you want your count to go? ");
countryCountProc = """ CREATE PROCEDURE countProc (OUT param1 INT)
BEGIN
SELECT COUNT(*) INTO param1 FROM searcher_country;
END;"""
readyFunction = """
CREATE FUNCTION ready(id INT)
returns CHAR(50)
return 'The program has been initialized';
"""
cursor.execute(countryCountProc);
cursor.execute(readyFunction);
outFile = '/tmp/testingCount';
print cursor.execute('CALL countProc(@a); SELECT @a INTO OUTFILE \'{0}\';'.format(outFile));
yearIndex = 2;
while True:
value = str(ws.cell(row=1,column=yearIndex).value);
try:
sql = 'INSERT INTO searcher_year (year) values (\'{0}\')'.format(value.encode("utf8"))
cursor.execute(sql);
except Exception as e:
print sql
print e
yearIndex = yearIndex + 1
if value == '2011':
print yearIndex-1;
break;
countryIndex = 2;
while True:
value = ws.cell(row=countryIndex,column=1).value.replace('\'','\\\'');
try:
sql = 'INSERT INTO searcher_country (country) values (\'{0}\')'.format(value.encode("utf8"))
cursor.execute(sql);
except Exception as e:
print sql
print e
countryIndex+=1
if value == "Saba":
print countryIndex-1;
break;
cursor.execute('SELECT countryId from searcher_country');
results = [int(item[0]) for item in cursor.fetchall()]
minCountryId = min(results);
maxCountryId = max(results);
cursor.execute('SELECT yearId from searcher_year');
results = [int(item[0]) for item in cursor.fetchall()]
minYearId = min(results);
maxYearId = max(results);
for i in xrange(500):
yearId = random.randint(350,370);
countryId = random.randint(3800,3820)
data = round(random.random()*10,2);
sql = 'INSERT INTO searcher_data (country_id,year_id,stat) values ({0},{1},\'{2}\')'.format(countryId,yearId,str(data))
cursor.execute(sql);
connection.execute('SELECT ready(1) INTO OUTFILE {0}'.format(outFile))
connection.commit();
cursor.close();