python學習筆記-Day11-- MySQLdb

python 連接 mysql 數據庫使用的是python中的 MySQLdb 模塊

使用該模塊前需要安裝

可以使用源碼安裝也可以使用pip安裝  或者使用ubuntu的apt-get 進行安裝.

這裏不做介紹

操作數據庫涉及四個基本的操作

增刪改查

關於數據庫的操作可以自行查找相關資料


MySQLdb 模塊的使用方法如下:

import MySQLdb
#創建數據庫連接
conn = MySQLdb.connect(host="127.0.0.1",user="root",passwd="123123",db="testdb",chatset="utf8")
cu = conn.cursor()
# 設置查詢語句
selectSQL = "select * from user"
selectResult = cu.execute(selectSQL)
#設置插入語句
insertSQL = "insert INTO user(name,group) VALUES(%s,%s)"
insertDate = [("user01","dba"),("user02","mgr"),("user03","staff")]
insertResult = cu.execute(selectSQL)
#設置更新語句
updateSQl = "update user set name=%s where NAME =%s"
updateData = ("newuser","user03")
updateResult = cu.execute(selectSQL)
#設置刪除語句
delSQl = "delete from user WHERE name=%s"
delData = ("newuser")
delResult = cu.execute(selectSQL)
print cu.fetchall()
conn.commit()
cu.close()
conn.close()


在使用中需要注意幾個問題

MySQLdb.connect 的參數很多,這裏只是涉及了常用的,通過看源碼可以看其他參數


fetch有三種情況

fetchone()   # 返回一條結果行

fetchmany(size=None)  #  接收size條返回結果行

fetchall()     # 接收全部的返回結果行

關於commit功能   autocommit 默認沒有打開,所以如果使用的是,支持事務的存儲引擎的時候,每次執行完事務後,需要手動commit,否則數據不會寫入數據庫.



參考

http://www.cnblogs.com/wupeiqi/articles/5095821.html


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章