python命令不同步;你现在不能运行这个命令"

时间:2016-02-16 17:52:56

标签: python mysql

我正在尝试运行这个小的python脚本,它将数据插入到MacOS下的mySql数据库中,但是它给了我以下错误:

  

文件" inserter.py",第58行,in           cursor.execute(' SELECT countryId from searcher_country');

     

文件" build / bdist.macosx-10.9-intel / egg / MySQLdb / cursors.py",第205行,执行

     

文件" build / bdist.macosx-10.9-intel / egg / MySQLdb / connections.py",第36行,在defaulterrorhandler中       _mysql_exceptions.ProgrammingError :( 2014年,"命令不同步;您现在无法运行此命令")

脚本:

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();

1 个答案:

答案 0 :(得分:0)

您没有在查询执行后释放游标。请包括 connection.commit(); cursor.close(); 在每个执行语句之后