Monday, September 24, 2012

INSERT parameterized mysql python



http://bytes.com/topic/python/answers/166025-python-mysql-insert-null

cursor's execute method has two parameteres:

1) SQL query with placeholders
2) parameters

For example:

var1 = "Joe's dog"
cur.execute("insert into mytable(col1) values (%s)", (var1,))
var1 = None
cur.execute("insert into mytable(col1) values (%s)", (var1,))

if you use MySQLdb (the most sensible choice for a MySQL Python database
adapter).

Because MySQLdb uses the pyformat param style, you use the %s
placeholder always, no matter which type your parameter will be.





The second argument to execute() should be a tuple (or list).
Please change your code to:
cursor.execute("INSERT INTO tableName (Length) VALUES (%s);", (length2,))









No comments:

Post a Comment