2012-03-16 59 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