0

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
4

2 Answers 2

1

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))
Sign up to request clarification or add additional context in comments.

2 Comments

I can only pass a max of 4 arguments. but thanks anyway
I don't know what that means. There are six arguments here.
0

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

thanks, what does the u at the front of the sql statement do?
u'' is used for utf-8 encoding string if you use a string that have special character like è é ecc.. this prevents encoding problems
This is wrong. You've now totally unnecessarily opened yourself up to SQL injection attacks. Do not do this.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.