2017-07-29 89 views
-1

我一直試圖從python使用MySQLdb接口插入MySQL數據庫。雖然我已經能夠成功地執行選擇查詢,但我的插入查詢卻什麼都不做。它們不會返回錯誤,但也不會向數據庫添加任何內容。無法使用MySQLdb插入MySQL數據庫python

我簡化了我的程序。

db = MySQLdb.connect(host='127.0.0.1',user=...,passwd=...,db=...) 
cursor = db.cursor() 
cursor.execute("""INSERT INTO user_event_log (username, major_event_id, minor_event_id, value, date) VALUES ('Test', 1, 1, '0.1', '2017-07-29')""") 

不知道我是否犯了一個非常愚蠢的錯誤,但我不明白爲什麼沒有插入任何東西。

回答

0

您需要提交數據庫更改並關閉數據庫。 請按照下面的代碼更改:

import MySQLdb 

# Open database connection 
db = MySQLdb.connect(host='127.0.0.1',user=...,passwd=...,db=...) 

# prepare a cursor object using cursor() method 
cursor = db.cursor() 
sql = """INSERT INTO user_event_log (username, major_event_id, minor_event_id, value, date) VALUES ('Test', 1, 1, '0.1', '2017-07-29')""" 
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() 

# disconnect from server 
db.close() 
0

您需要爲連接添加MySQLdb.commit()。 (Source

這就像在代碼的末尾添加db.commit()一樣簡單。

希望它有幫助!