[英]Not showing data in database after insertion using python
我正在使用python 2.7和MySQL作為數據庫。 在我的python程序中有一個INSERT
查詢,如下所示:
cursor.execute("insert into login(username,passw)values('"+i.username+"','"+i.password+"')")
result=cursor.execute("select * from login")
print cursor.fetchall()
當我簽入數據庫時,沒有任何條目。 但是在我的python代碼中選擇之后,當我打印結果時,它會顯示插入的數據。 我也不使用任何交易記錄。
您需要為數據庫提交事務以使插入成為永久性的,並且需要使用SQL參數來防止SQL注入攻擊和一般的引用錯誤:
cursor.execute("insert into login (username, passw) values (%s, %s)", (i.username, i.password))
connection.commit()
在提交之前,插入的數據僅對python程序可見; 如果根本不提交,則數據庫將再次放棄所做的更改。
或者,您可以打開自動提交模式:
connection.autocommit()
開啟自動提交后,您的插入內容將立即被提交。 請注意這一點,因為如果您需要將數據插入到相互依賴的多行和/或表中,則可能導致數據不一致。
您還需要在執行語句之后提交數據。 在完成插入或更新數據后調用此方法很重要,因為默認情況下 Python連接器不會自動提交 。
# 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()
如果使用mysql-python,則可以設置連接選項以啟用自動提交功能。
conn = mysql.connection(host, port, autocommit=True)
# or
conn = mysql.connection(host, port)
conn.autocommit(True)
您可以在此處查看更多詳細信息
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.