我有一个有 9 列的表格,前三列都是文本,最后 6 列设置为 INT。

当我插入文本字段时,一切都按预期工作

conn = pymysql.connect(host='', port=, user='', passwd='', db='')
cur = conn.cursor()
cur.execute("INSERT INTO table(Name) VALUES ('Sample Name')")

该代码运行良好,并允许我将名称插入到我的数据库中。但是,当为我的整数内容运行插入语句时,我遇到了各种麻烦。

我已经尝试了以下所有方法:
cur.execute("INSERT INTO table(Left Avg) VALUES (5)")
cur.execute("INSERT INTO table(Left Avg) VALUES (%s)", (5))
cur.execute("INSERT INTO table(Left Avg) VALUES (%s)" % (5))
cur.execute("""INSERT INTO mlb_data(Left Avg) VALUES (%s)""" % (5))

基本上,无论我在将整数插入表中时尝试什么,我都会收到以下错误。
Traceback (most recent call last):
File "testing.py", line 12, in <module>
cur.execute("""INSERT INTO mlb_data(Left Avg) VALUES (%s)""" % (5))
File "build/bdist.macosx-10.7-intel/egg/pymysql/cursors.py", line 117, in execute
File "build/bdist.macosx-10.7-intel/egg/pymysql/connections.py", line 189, in     defaulterrorhandler
pymysql.err.ProgrammingError: (1064, u"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 'Left   Avg) VALUES (5)' at line 1")

我曾尝试将 MySQl 平板电脑更改为 VarChar 而不是 INT,但无论何时尝试插入数字,我都会收到错误消息。

我在这里缺少什么?

编辑:
我不知道我之前是否没有尝试过,或者我的格式不正确,但我想通了。
num = 5.23947824987
cur.execute("INSERT INTO mlb_data(LeftAvg) VALUES (%s)", (num,))

工作顺利。这是正确的,还是我太幸运了?

最佳答案

怎么样

cur.execute("INSERT INTO table(`Left Avg`) VALUES (?)", (5,))

假设 'Left Avg' 是列名,您应该尽量避免列名中的空格作为一般规则

关于python - 无法通过 Python 和 pymysql 插入 MySQL,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/16200744/

10-12 01:06
查看更多