Reputation: 2264
I'm trying to insert a row into a table that I've set up in a database.
My Code:
cursor.execute("""INSERT INTO scan (prefix, code_id, answer, station) VALUES(%s, %s, %s, %s, timestamp, comport)""",[(prefix, code_id, answer, station)])
I'm getting for an error that is saying that it doesn't like what is in "[]".
I don't completely understand how "%s" works. I've tried many examples and all have failed me.
I got this example from http://mysql-python.sourceforge.net/MySQLdb.html
Upvotes: 0
Views: 7460
Reputation: 6460
cursor.execute('INSERT INTO scan (prefix, code_id, answer, station) VALUES("%s", "%s", "%s", "%s")' %(prefix, code_id, answer, station))
You might get an error if if you miss the ""
around %s
ie if you use simply %s
instead of this "%s"
in values.
Upvotes: 0
Reputation: 909
Why do you have the parameters inside two sets of brackets? The second argument should be a sequence containing four items, to match the four %s
s in your query. Instead, you have given it a list containing one item: that item is a sequence with four items in it.
Instead, try:
cursor.execute("""INSERT INTO scan (prefix, code_id, answer, station) VALUES(%s, %s, %s, %s, timestamp, comport)""",(prefix, code_id, answer, station))
Upvotes: 2
Reputation: 1843
You can use Python's new 'format' string method:
cursor.execute("""INSERT INTO scan (prefix, code_id, answer, station) VALUES({}, {}, {}, {}, timestamp, comport)""".format(prefix, code_id, answer, station))
You can also number the parameters, like "{0}", "{1}", and so on. This might be required depending on your Python version (I think 2.6 already supports parameters with no numbering).
For a reference on using this, check http://docs.python.org/library/string.html#format-examples
Upvotes: -1