python 命令不同步;你现在不能运行这个命令”
Posted
技术标签:
【中文标题】python 命令不同步;你现在不能运行这个命令”【英文标题】:python Commands out of sync; you can't run this command now" 【发布时间】:2016-05-28 03:40:27 【问题描述】:我正在尝试运行这个在 MacOs 下将数据插入到 mysql 数据库的小型 python 脚本,但是它给了我以下错误:
文件“inserter.py”,第 58 行,在 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 行,默认错误处理程序 _mysql_exceptions.ProgrammingError: (2014, "Commands out of sync; you can't run this command now")
脚本:
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();
【问题讨论】:
使用查询参数而不是嵌入它们。至少,如果你这样做了,你需要escape他们。 【参考方案1】:您没有在查询执行后释放光标。请包括
connection.commit(); cursor.close();
在每个执行语句之后
【讨论】:
以上是关于python 命令不同步;你现在不能运行这个命令”的主要内容,如果未能解决你的问题,请参考以下文章