python插入mysql查询

2hh7jdfx  于 2021-06-21  发布在  Mysql
关注(0)|答案(3)|浏览(255)

我尝试在python 2.7中执行该代码:

import MySQLdb, getopt
import MySQLdb.cursors
a = "TEST"
b = 1
c = 2
d = 3
e = 4
db = MySQLdb.connect(host="localhost", user="root",passwd="password", 
db="database") # name of the data base
cur = db.cursor(MySQLdb.cursors.DictCursor)
query = ""INSERT INTO `HD_coords` (`name`, `west`, `north`, `east`, `south`) 
VALUES (%s, %s, %s, %s, %s)"",(a, b, c, d, e)
cur.execute(query)
cur.close() 
db.commit()

所以我得到一个错误:

Traceback (most recent call last):
  File "MYSQL_TEST.py", line 15, in <module>
    cur.execute(query)
  File "/usr/lib/python2.7/dist-packages/MySQLdb/cursors.py", line 223, in 
execute
    self.errorhandler(self, TypeError, m)
  File "/usr/lib/python2.7/dist-packages/MySQLdb/connections.py", line 36, in 
defaulterrorhandler
    raise errorvalue
TypeError: query() argument 1 must be string or read-only buffer, not tuple

nom是varchar类型(255)。西、北、南、东为int型。有什么线索吗?
泰晤士河

x0fgdtte

x0fgdtte1#

您必须将您的连接对象放入可以处理连接异常的try-and-expect块中
发生此错误是因为它在异常之前提供异常

pprl5pva

pprl5pva2#

可以使用.format(**locals())将变量替换为其值:

cur = db.cursor(MySQLdb.cursors.DictCursor)
query = "INSERT INTO HD_coords (name, west, north, east, south) VALUES ({a},{b}, {c}, {d}, {e})".format(**locals())
cur.execute(query)
cur.close() 
db.commit()
kse8i1jr

kse8i1jr3#

你的语法不正确。执行插入的代码应该如下所示:

cur = db.cursor(MySQLdb.cursors.DictCursor)
query = ("INSERT INTO HD_coords (name, west, north, east, south) " +
         "VALUES (%s, %s, %s, %s, %s)")
cur.execute(query, (a, b, c, d, e))
cur.close() 
db.commit()

首先定义一个带有占位符的sql语句,您似乎已经在这样做了。然后,将值绑定到调用中的占位符 cursor.execute .

相关问题