python使用mysql資料庫,增刪改查
阿新 • • 發佈:2018-11-08
需要注意的是:
mysql資料建立的表中,欄位名中不能出現key當欄位名。
因為使用python中呼叫插入語句時,不能成功插入。
匯入庫
import MySQLdb
連線資料庫
#開啟資料庫連線
db = MySQLdb.connect(localhost_name, user_name , password ,database_name,charset='utf8')
#使用cursor()方法獲取操作遊標
cursor = db.cursor()
增加一條資料
#Add 新增資料 def insert( word , wordpart): sql = "INSERT INTO stopword(word,wordPart)VALUES('" + word + "','" + wordpart + "')" print("插入資料:" , sql)
刪除一條資料
sql = "DELETE FROM stopword WHERE word = '" + word + "';"
更新一條資料
sql = "UPDATE stopword set word='" + word + "',wordPart='" + new_wordpart + "' WHERE word='" + word +"',wordPart='" + wordpart+"';"
以上三種操作是針對資料庫直接進行的,所以,當操作完成後,需要儲存操作的內容,否則不能儲存成功!
try: # 執行sql語句 cursor.execute(sql) # 提交到資料庫執行 db.commit() except: # 發生錯誤時回滾 db.rollback() print('儲存資料失敗!')
查詢資料
sql = "SELECT id,word,wordPart FROM stopword WHERE word='" + word + "';" cursor.execute(sql) results = cursor.fetchall() #results表示搜尋出來的結果 #顯示查詢的結果 for row in results: fid = row[0] fword = row[1] fwordPart = row[2] print('id =%s, 詞 = %s , 詞性 = %s'%(fid , fword , fwordPart))