2012-03-16 58 views
0

我用MySQLdb创建了一个数据库。
在数据库中,我有名字student一个表列:设置%s的Mysqldb更新错误

 
id(is int), 
id_user(is int), 
f_name(is str), 
l_name(is str) 

我想更新一行。
我的代码如下:

db=mdb.connect(host="localhost", use_unicode="True", charset="utf8", 
       user="", passwd="", db="test")       
# prepare a cursor object using cursor() method 
cursor = db.cursor() 

sql="""SELECT id_user FROM student""" 

try: 
    # Execute the SQL command 
    cursor.execute(sql) 
    # Commit your changes in the database 
    db.commit() 
except: 
    # Rollback in case there is any error 
    db.rollback() 

rows = cursor.fetchall() 

the=int(7) 
se=str('ok') 
for row in rows: 
    r=int(row[0]) 
    if r==the:   
     sql2 = """UPDATE student 
       SET f_name=%s 
       WHERE id_user = %s"""% (se,the) 

       # Execute the SQL command 
     cursor.execute(sql2) 
     # Commit your changes in the database 
     db.commit() 

     db.rollback() 
# disconnect from server 
db.close() 

当我运行它,我采取的错误是列名称为好,为什么?
任何人都可以帮我找到我做错了吗?

+1

你应该附上字符串转换为单引号。 – 2012-03-16 18:53:29

回答

2

你应该像这样运行查询:

sql2 = """UPDATE student 
      SET f_name = %s 
      WHERE id_user = %s""" 
cursor.execute(sql2, (se, the)) 

不要使用字符串插值,让数据库驱动程序句柄传递参数给你。否则,你必须处理像这样的语法错误,或者更糟糕的是,SQL注入。

更多详细信息here

+0

+1适用于链接。伟大的东西 – bernie 2012-03-16 19:00:36

+0

谢谢它的作品! – TLSK 2012-03-16 19:10:43

+0

我不知道什么代码使用你的或ruakh.I将在稍后看到:) – TLSK 2012-03-16 19:13:08

3

str不会环绕其用引号引起争论,所以你的说法是这样的:

UPDATE student SET f_name=ok WHERE id_user = 7 

时,它需要是这样的:

UPDATE student SET f_name='ok' WHERE id_user = 7 

所以,要么改变这一行:

   SET f_name=%s 

对此:

   SET f_name='%s' 

要不改变这一行:一旦你开始使用用户提供的数据

se="'" + str('ok') + "'" 

虽然我建议你阅读有关SQL injection,这将成为一个问题:

se=str('ok') 

本而不是硬编码的值。

+0

+1的详细解释,虽然 - 作为@Lukas提到 - DB-API应该真的在这里使用;正如你暗示的SQL注入评论 – bernie 2012-03-16 19:06:05

+0

感谢它与你的代码 – TLSK 2012-03-16 19:11:41

0

你应该总是用引号括起你的数据。

除了%s完全使用'%s'之外,您不需要的唯一类型是数字类型,但即使在那里,我也会将%d与'%d'相加,因为它更节省。

在插入或更新数据到数据库之前,至少应该使用db.escape_string(your_data)。

或者看看MySQLdb的的使用PDO风格:

http://mysql-python.sourceforge.net/MySQLdb.html#some-examples

c=db.cursor() 
max_price=5 
c.execute("""SELECT spam, eggs, sausage FROM breakfast 
     WHERE price < %s""", (max_price,)) 
+0

感谢您的提示! – TLSK 2012-03-16 19:19:43