views:

46

answers:

4
import MySQLdb    
import random

db = MySQLdb.connect (host = "localhost", user = "python-test", passwd = "python", db = "python-test")

cursor = db.cursor()

var = .3

sql = "INSERT INTO RandomInt 
         (RAND) 
       VALUES 
         (var)" # RandomInt is the name of the table and Rand is the Column Name

cursor.execute(sql)

db.commit()
db.close()

I get an error saying that "Operational Error: (1054, "Unknown column 'var' in 'field list'") Why do I get this error and how do I fix this although I have already defined var?

+1  A: 

Your sql appears to MySQL as:

INSERT INTO RandomInt (RAND) VALUES (var)

To actually have the string substitute var, try this:

sql = "INSERT INTO RandomInt (RAND) VALUES (%d)"  % (var,)

Now, MySQL should see:

INSERT INTO RandomInt (RAND) VALUES (0.3)

NOTE: Adam Bernier is right about sql injection. See the cursor.execute doc for parameter substitution as well as his answer.

ars
+1; beat me. Nitpicks: 1) vulnerable to SQL-injection, and 2) the `%d` should be `%s`.
Adam Bernier
-1 vulnerable to SQL-injection, SQL has to be retranslated each time if being done in a loop ... there's rarely a good reason to do it this way and pushing it at a beginner without any remarks at all is disgraceful.
John Machin
John: Huh? That's why I added the remark at the end and pointed to Adam's answer. The timestamp shows it was ~3 minutes before your comment.
ars
@ars: I type slowly / I got a cup of copy / whatever. So what? The fact that you changed your answer is irrelevant; you shouldn't have contemplated such an answer in the first place.
John Machin
+2  A: 

As written, var is being sent to MySQL as a string.
Give this a shot instead:

sql = "INSERT INTO RandomInt (RAND) VALUES (%s)"
cursor.execute(sql, (var,))

Edit:

>>> import MySQLdb
>>> MySQLdb.paramstyle
'format'

MySQLdb's paramstyle is format; which, according to the DB-API is %s:

            'format'        ANSI C printf format codes, 
                            e.g. '...WHERE name=%s'
Adam Bernier
cursor.execute is definitely better. Doesn't it take "?" for parameters though? or is the "%s" also acceptable?
ars
@ars: added background info regarding `paramstyle`.
Adam Bernier
Nice, thank you.
ars
+1  A: 

This will fix one issue:

sql = "INSERT INTO RandomInt (RAND) VALUES (%s)" 
cursors.execute(sql, (var,))

What remains is the name of the table where you write into, 0.3 is not an int.

Edit: paramstyle of mysqldb is %s not ?.

DiggyF
Minor point: MySQLdb uses `%s` as placeholder.
Adam Bernier
I think ? should be %s. Depends on the `paramstyle`.
DiggyF
cursors.execute(sql, var)(1) multiple cursors ?-)(2) 2nd arg should be a tuple `(var, )`
John Machin
A: 
var = .3
sql = "INSERT INTO RandomInt (RAND) VALUES (%s)" 
cursor.execute(sql, (var,))
John Machin