2017-07-27 48 views
2

Python的MySQLdb模塊應該使用SQL語句字符串中的格式說明符來實現佔位符。我下面從MySQL食譜MySQLdb佔位符實現不起作用

import sys 
import MySQLdb 
import Cookbook 

try: 
    conn = Cookbook.connect() 
    print("Connected") 
except MySQLdb.Error as e: 
    print("Cannot connect to server") 
    print("Error code:", e.args[0]) 
    print("Error message:", e.args[1]) 
    sys.exit (1) 

cursor = conn.cursor() 
cursor.execute (""" 
       INSERT INTO profile (name,birth,color,foods,cats) 
       VALUES(%s,%s,%s,%s,%s) 
       """,("Josef", "1971-01-01", None, "eggroll", 4)) 

個例但是,當我從殼

mysql> SELECT * FROM profile WHERE name LIKE 'J%'; 
+----+--------+------------+-------+----------------+------+ 
| id | name | birth  | color | foods   | cats | 
+----+--------+------------+-------+----------------+------+ 
| 7 | Joanna | 1952-08-20 | green | lutefisk,fadge | 0 | 
+----+--------+------------+-------+----------------+------+ 

檢查很明顯,沒有什麼是inserted.Why? 如果我添加cursor.commit建議

cursor.commit() 
AttributeError: 'Cursor' object has no attribute 'commit' 
+0

檢查編輯的答案。將光標更改爲conn – Aniket

回答

1

您沒有提交事務。

最後在執行查詢後添加conn.commit()

cursor = conn.cursor() 
cursor.execute (""" 
      INSERT INTO profile (name,birth,color,foods,cats) 
      VALUES(%s,%s,%s,%s,%s) 
      """,("Josef", "1971-01-01", None, "eggroll", 4)) 
conn.commit() 
+0

謝謝,現在按預期工作。 – MishaVacic

+0

很高興幫助。 – Aniket