我在ubuntu中使用了相同的代码并且工作正常但是当我尝试在Windows中运行它时它给了我一个“()”输出。可能是什么原因。我是这个领域的新手我需要帮助.`
import csv
import string
import MySQLdb
with open('cool1.txt','r') as csvfile:
scoreFileReader=csv.reader(csvfile)
scoreList=[]
for row in scoreFileReader:
if len(row) !=0:
scoreList=scoreList + [row]
csvfile.close()
print(scoreList)
temp=str(scoreList).translate(string.maketrans('', ''), '[]\'')
#print(temp)
db = MySQLdb.connect("localhost","root","","test123" )
#setup cursor
cursor = db.cursor()
#create anooog1 table
cursor.execute("DROP TABLE IF EXISTS db1234")
sql = """CREATE TABLE db1234 (
uid VARCHAR(100) NOT NULL,
price INT(100) NOT NULL)"""
cursor.execute(sql)
try:
cursor.execute("""INSERT INTO db1234 VALUES (%s,%s)""",(scoreList))
db.commit()
except:
db.rollback()
#how table
cursor.execute("""SELECT * FROM db1234;""")
print cursor.fetchall()
db.close()
,文本文件数据如下所示:
E0 C1 7F 7A
0
删除后除了错误就像这些
[['E0 C1 7F 7A'], ['0']]
Traceback (most recent call last):
File "csvfile_writer2.py", line 31, in <module>
cursor.execute("""INSERT INTO db1234 VALUES (%s,%s)""",(scoreList))
File "C:\Python27\lib\site-packages\MySQLdb\cursors.py", line 174, in execute
self.errorhandler(self, exc, value)
File "C:\Python27\lib\site-packages\MySQLdb\connections.py", line 36, in defaulterrorhandler
raise errorclass, errorvalue
_mysql_exceptions.ProgrammingError: (1064, 'You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near \'),("\'0\'",))\' at line 1')
在使用except子句之前它已经来了
C:\Users\supar\Desktop>python csvfile_writer2.py
[['E0 C1 7F 7A'], ['0']]
()
C:\Users\supar\Desktop>
答案 0 :(得分:1)
您有两个占位符,每次迭代只能插入一个项目。所以只需将占位符数量减少到一个。
由于您要插入容器容器,请使用{{3}},例如:
cursor.executemany("""INSERT INTO db1234 VALUES (%s)""", scoreList)