python未将数据插入mysql

2024-04-20 06:54:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我在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')

在它到来之前

C:\Users\supar\Desktop>python csvfile_writer2.py
[['E0 C1 7F 7A'], ['0']]
()

C:\Users\supar\Desktop>

Tags: csvfileinpyimportexecutedblinecursor
1条回答
网友
1楼 · 发布于 2024-04-20 06:54:32

您有两个占位符,每个迭代只需要插入一个项。所以只需将占位符的数量减少到一个

既然有一个容器要插入,就使用^{},例如:

cursor.executemany("""INSERT INTO db1234 VALUES (%s)""", scoreList)

相关问题 更多 >