首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >python无法在mysql中插入数据

问python无法在mysql中插入数据
EN

Stack Overflow用户
提问于 2017-08-29 01:57:47
回答 1查看 36关注 0票数 0

我在ubuntu中使用过同样的代码,它运行得很好,但是当我尝试在windows中运行它时,它给了我一个"()“output.What,这可能是.I对这个领域不熟悉的原因,因为我需要帮助。

代码语言:javascript
复制
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()

文本文件数据如下所示:

代码语言:javascript
复制
E0 C1 7F 7A

0

删除except后,出现如下错误

代码语言:javascript
复制
[['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')

在with except子句之前它即将到来

代码语言:javascript
复制
C:\Users\supar\Desktop>python csvfile_writer2.py
[['E0 C1 7F 7A'], ['0']]
()

C:\Users\supar\Desktop>
EN

回答 1

Stack Overflow用户

发布于 2017-08-29 02:11:15

您有两个占位符,并且每次迭代中只有一个要插入的项。因此,只要将占位符的数量减少到一个即可。

由于您有一个容器容器要使用.executemany()插入,例如:

代码语言:javascript
复制
cursor.executemany("""INSERT INTO db1234 VALUES (%s)""", scoreList)
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/45924843

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档