Antoine
Antoine

Reputation: 3

PYTHON INSERT MYSql query

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

Upvotes: 0

Views: 156

Answers (3)

A. Colonna
A. Colonna

Reputation: 872

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

Upvotes: 0

Tim Biegeleisen
Tim Biegeleisen

Reputation: 522817

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.

Upvotes: 1

manan5439
manan5439

Reputation: 958

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

Upvotes: 0

Related Questions