I am trying to work out what is wrong with my code. I am trying to enter data into a mysql, and python doesn't seem to like how i have done something.
Test Data
Name = "TestRegion"
Perent= "perent"
x1 = -100.0
x2 = -150.0
z1 = 94.0
z2 = 200.0
Code
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()
my issue I am guessing is how I am trying to pass the values to the sql statment.
my Error message is
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
-
do u want know other way of same implementation which is easysundar nataraj– sundar nataraj2014年04月17日 12:35:43 +00:00Commented Apr 17, 2014 at 12:35
-
yeah, always up for another way.TheDuncan– TheDuncan2014年04月17日 13:06:04 +00:00Commented Apr 17, 2014 at 13:06
-
u can use peeweee.. easy library .. peewee.readthedocs.org/en/latest/peewee/installation.html for all sort of database actionssundar nataraj– sundar nataraj2014年04月17日 13:07:08 +00:00Commented Apr 17, 2014 at 13:07
-
stackoverflow.com/questions/372885/…sundar nataraj– sundar nataraj2014年04月17日 13:09:32 +00:00Commented Apr 17, 2014 at 13:09
2 Answers 2
The MySQL adapter does not use ? for placeholders, it uses %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))
answered Apr 17, 2014 at 12:42
Daniel Roseman
602k68 gold badges911 silver badges924 bronze badges
Sign up to request clarification or add additional context in comments.
2 Comments
TheDuncan
I can only pass a max of 4 arguments. but thanks anyway
Daniel Roseman
I don't know what that means. There are six arguments here.
try this:
sql = u'INSERT INTO RegionName (Name, Perent, X1, X2, Z1, Z2) VALUES ("%s","%s",%d,%d,%d,%d)'% (Name, Perent, x1, x2, z1, z2)
cur.execute(sql)
3 Comments
TheDuncan
thanks, what does the u at the front of the sql statement do?
archetipo
u'' is used for utf-8 encoding string if you use a string that have special character like è é ecc.. this prevents encoding problems
Daniel Roseman
This is wrong. You've now totally unnecessarily opened yourself up to SQL injection attacks. Do not do this.
default