Consider the following code: The first query does not work while the second does. The problem is... since I need to compose a query beforehand via a function this function returns a variable as 'val'. So I need to get the first query to work. The second query is only added by example to show what happens when the content of 'val' is used literally. Please help! So, I want to insert a datetime but 'None' is also to be accepted. The current error is:
query = query % db.literal(args)
TypeError: not enough arguments for format string
Now the script:
#!/usr/bin/python
import MySQLdb as mdb
def prepare():
# Assume a database named 'db_test'
conn = mdb.connect(host = 'localhost', \
user = 'test', \
passwd = 'test', \
db = 'db_test')
cur = conn.cursor()
cur.execute("DROP TABLE IF EXISTS TBL_TEST")
cur.execute("CREATE TABLE TBL_TEST(Moo1 DATETIME, Moo2 DATETIME)")
return cur
if __name__ == '__main__':
qry = "INSERT INTO TBL_TEST (Moo1, Moo2) VALUES (%s, %s)"
val = "('2012-04-03 08:40:39', None)"
cur = prepare()
cur.execute(qry, val) # NOK
cur.execute("INSERT INTO TBL_TEST (Moo1, Moo2) VALUES (%s, %s)", ('2012-04-03 08:40:39', None)) # OK
Trust me - I searched the world but without any success.. Thanks in advance!