I'm trying to execute that code in 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()
So i'm getting this error :
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 is varchar type(255). west, north, south, east are int type. Any clue?
Thxx
Your syntax is off. The code doing the insertion should look something like this:
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()
First define a SQL statement with placeholders, which you already seem to be doing. Then, bind values to those placeholders in your call to cursor.execute
.
You have to put your connection object in try and expect block that can handle your connections exception
This error occurred because it's give exception before exception
You can use the .format(**locals()) which replace variable by their values:
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()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.