講解Python操作資料庫,完成簡單的增刪改查工作,以MySQL資料庫為例。
Python的MySQL資料庫操作模組叫MySQLdb,需要額外的安裝下。
通過pip工具安裝:pip install MySQLdb
MySQLdb模組,我們主要就用到串連資料庫的方法MySQLdb.Connect(),串連上資料庫後,再使用一些方法做相應的操作。
MySQLdb.Connect(parameters...)方法提供了以下一些常用的參數:
連線物件返回的connect()函數:
遊標對象也提供了幾種方法:
13.1 資料庫增刪改查
13.1.1 在test庫建立一張user表,並添加一條記錄
>>> conn = MySQLdb.Connect(host='192.168.1.244',user='root',passwd='QHyCTajI',db='test',charset='utf8')>>> cursor = conn.cursor()>>> sql = "create table user(id int,name varchar(30),password varchar(30))">>> cursor.execute(sql) # 返回的數字是影響的行數0L >>> sql = "insert into user(id,name,password) values('1','xiaoming','123456')">>> cursor.execute(sql)1L>>> conn.commit() # 提交事務,寫入到資料庫>>> cursor.execute('show tables') # 查看建立的表1L>>> cursor.fetchall() # 返回上一個遊標執行的所有結果,預設是以元組形式返回((u'user',),)>>> cursor.execute('select * from user') 1L>>> cursor.fetchall()((1L, u'xiaoming', u'123456'),)
13.1.2 插入多條資料
>>> sql = 'insert into user(id,name,password) values(%s,%s,%s)'>>> args = [('2','zhangsan','123456'), ('3','lisi','123456'),('4','wangwu','123456')] >>> cursor.executemany(sql, args)3L>>> conn.commit()>>> sql = 'select * from user'>>> cursor.execute(sql)4L>>> cursor.fetchall()((1L, u'xiaoming', u'123456'), (2L, u'zhangsan', u'123456'), (3L, u'lisi', u'123456'), (4L, u'wangwu', u'123456'))
args變數是一個包含多元組的列表,每個元組對應著每條記錄。當查詢多條記錄時,使用此方法,可有效提高插入效率。
13.1.3 刪除使用者名稱xiaoming的記錄
>>> sql = 'delete from user where name="xiaoming"'>>> cursor.execute(sql) 1L>>> conn.commit()>>> sql = 'select * from user' >>> cursor.execute(sql) 3L>>> cursor.fetchall() ((2L, u'zhangsan', u'123456'), (3L, u'lisi', u'123456'), (4L, u'wangwu', u'123456'))
13.1.4 查詢記錄
>>> sql = 'select * from user' >>> cursor.execute(sql) 3L>>> cursor.fetchone() # 擷取第一條記錄(2L, u'zhangsan', u'123456')>>> sql = 'select * from user' >>> cursor.execute(sql) 3L>>> cursor.fetchmany(2) # 擷取兩條記錄((2L, u'zhangsan', u'123456'), (3L, u'lisi', u'123456'))
13.1.4 以字典形式返回結果
預設顯示是元組形式,要想返回字典形式,使得更易處理,就用到cursor([cursorclass])中的cusorclass參數。傳入MySQLdb.cursors.DictCursor類:>>> cursor = conn.cursor(MySQLdb.cursors.DictCursor)>>> sql = 'select * from user'>>> cursor.execute(sql)3L>>> cursor.fetchall()({'password': u'123456', 'id': 2L, 'name': u'zhangsan'}, {'password': u'123456', 'id': 3L, 'name': u'lisi'}, {'password': u'123456', 'id': 4L, 'name': u'wangwu'})
13.2 遍曆查詢結果
#!/usr/bin/env python# -*- coding: utf-8 -*-import MySQLdbtry: conn = MySQLdb.Connect(host='127.0.0.1', port=3306, user='root', passwd='123456', connect_timeout=3, charset='utf8') cursor = conn.cursor() sql = "select * from user" cursor.execute(sql) for i in cursor.fetchall(): print iexcept Exception, e: print ("Connection Error: " + str(e))finally: conn.close() # python test.py(2L, u'zhangsan', u'123456')(3L, u'lisi', u'123456')(4L, u'wangwu', u'123456')
使用for迴圈遍曆查詢結果,並增加了異常處理。