我正在尝试找出我的代码有什么问题。我正在尝试将数据输入 mysql,但 python 似乎不喜欢我所做的事情。
测试数据
Name = "TestRegion"
Perent= "perent"
x1 = -100.0
x2 = -150.0
z1 = 94.0
z2 = 200.0
代码
def NewRegion(Name, Perent, x1, x2, z1, z2):
try:
con = SQLConnect()
cur = con.cursor()
sql = """INSERT INTO RegionName (Name, Perent, X1, X2, Z1, Z2) VALUES (?,?,?,?,?,?)"""
cur.execute(sql, (Name, Perent, x1, x2, z1, z2))
con.commit()
except mdb.Error, e:
con.rollback()
print "Error %d: %s" % (e.args[0],e.args[1])
finally:
if con:
con.close()
我猜测我的问题是我如何尝试将值传递给 sql 语句。
我的错误消息是
File "/usr/lib/python2.7/dist-packages/MySQLdb/cursors.py, line 159, in execute
query = query % db.literal(args)
TypeError: not all arguments converted during string formatting
最佳答案
MySQL 适配器不使用 ?
作为占位符,而是使用 %s
。
sql = """INSERT INTO RegionName (Name, Perent, X1, X2, Z1, Z2) VALUES (%s, %s, %s, %s, %s, %s)"""
cur.execute(sql, (Name, Perent, x1, x2, z1, z2))
关于python插入mysql,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23133135/