0

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

3 Answers 3

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

0

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()

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.