2013-04-18 68 views
1

我使用python 2.7和MySQL作爲數據庫。在我的Python程序有一個INSERT這樣的查詢:使用python插入後不顯示數據庫中的數據

cursor.execute("insert into login(username,passw)values('"+i.username+"','"+i.password+"')") 
result=cursor.execute("select * from login") 
print cursor.fetchall() 

當我在數據庫中查詢,沒有條目。但是,在我的Python代碼中選擇後,當我打印結果它顯示插入的數據。我也沒有使用任何交易聲明。

+3

您需要提交這些更改。 'connection.commit()' – RedBaron

回答

2

您還需要commit執行語句後的數據。在完成插入或更新數據之後調用此方法非常重要,因爲Python連接器不是auto commit by default

# Execute & Commit 
cursor.execute("insert into login(username,passw) values('%s','%s')", 
       i.username, i.password) 
# Commit the insert query! 
conn.commit() 

# Fetch Result 
result=cursor.execute("select * from login") 
print cursor.fetchall() 
4

您需要提交您的交易數據庫,使您的插入永久性的,你需要使用SQL參數來防止SQL注入攻擊,一般報價錯誤:

cursor.execute("insert into login (username, passw) values (%s, %s)", (i.username, i.password)) 
connection.commit() 

直到你提交,你插入的數據只會被你的python程序看到;如果您完全沒有提交,那麼數據庫會再次將丟棄爲

或者,您也可以在切換自動提交模式:

connection.autocommit() 

在自動提交切換後,您的插入將致力於立即。請小心,因爲如果您需要將數據插入到相互依賴的多行和/或表中,這可能會導致數據不一致。

0

如果您使用mysql-python,則可以設置連接選項以啓用自動提交功能。

conn = mysql.connection(host, port, autocommit=True) 

# or 
conn = mysql.connection(host, port) 
conn.autocommit(True) 

你可以看到更多的細節here

相關問題