第10章 Python数据库编程
本章的知识点:
1、ODBC的连接方式;
2、DAO的连接方式;
3、ADO的连接方式;
4、访问Oracle数据库的各种方法;
5、MySQL数据库的访问;
6、SQLite数据库的使用;
10.1 Python环境下的数据库编程
10.1.1 通过ODBC访问数据库
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 import odbc, dbi
2 import time
3 db = odbc.odbc("addresses/sctt/tiger")
4 curser = db.cursor()
5 curser.execute("select * from address order by id desc")
6 for col in curser.description:
7 print (col[0], col[1])
8 result = curser.fetchall()
9 for row in result:
10 print (row)
11 print (row[1], row[2])
12 timeTuple = time.localtime(row[3])
13 print (time.strftime("%Y/%m/%d",timeTuple))
10.1.2 使用DAO对象访问数据库
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 import win32com.client 2 engine = win32com.client.Dispatch("DAO.DBEngine.36") 3 db = engine.OpenDatabase("addresses.mdb") 4 rs = db.OpenRecordset("address") 5 rs = db.OpenRecordset("select * from address") 6 # 插入数据 7 db.Execute(""" 8 insert into address(name, address, createtime) 9 values('赵涛','上海虹口', '2008-3-25') 10 """) 11 while not rs.EOF: 12 print ((rs.Fields("address").Value).encode('gb2312')) 13 rs.MoveNext
10.1.3 使用ActiveX Data Object访问数据库
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 import win32com.client 2 conn = win32com.client.Dispatch('ADODB.Connection') 3 dsn = 'Provider=OraOLEDB.Oracle;PLSQLRSet=1;Password=tiger;UaerID=scott;DataSource=ORCL' 4 conn.Open(dsn) 5 rs = win32com.client.Dispatch('ADODB.Recordset') 6 sql = """ 7 from emp a,emp b,dept c where a.sal > 2500 8 and a.mgr = b.empno 9 and a.mgr = b.empno(+) 10 order by a.sal""" 11 rs.Open(sql, conn) 12 rs.MoveFirst() 13 li = list() 14 while notrs.EOF: 15 d = dict() 16 for x in range(rs.Fields.Count): 17 key = rs.Fields.Item(x).Name 18 value = rs.Fields.Item(x).Value 19 d.setdefault(key, value) 20 li.append(d) 21 print (rs.Fields("薪水").Value, rs.Fields("工作").Value,\ 22 rs.Fields("部门").Value, rs.Fields("姓名").Value, rs.Fields("管理者").Value) 23 rs.MoveFirst() 24 for d in li: 25 for key in d.keys(): 26 print (key.encode("gb2312"), d.get(key),) 27 print () 28 conn.Close()
10.1.4 Python连接数据库的专业模块
1) cx_Oracle模块
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 import cx_Oracle 2 connection = cx_Oracle.connect("scott", "tiger", "ORCL") 3 cursor = connection.cursor() 4 sql = """select a.ename 姓名,a.job 工作, a.sal 薪水, c.dname 部门,b.ename 管理者 5 from emp a,emp b,dept cwhere a.sal > 2500 6 and a.mgr = b.empno 7 and a.mgr = b.empno(+) 8 order by a.sal""" 9 cursor.execute(sql) 10 for x in cursor.fetchall(): 11 for value in x: 12 print (value,) 13 print () 14 cursor.close() 15 connection.close()
2) MySQLdb模块
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 import os,sys 2 import MySQLdb 3 # 连接数据库 4 try: 5 conn = MySQLdb.connect(host='localhost', user='root', passwd='',db='ADDRESSBOOKDB') 6 except Exception,e: 7 print (e) 8 sys.exit() 9 cursor = conn.cursor() 10 sql = "insert into address(name, address) value (%s, %s)" 11 values = (("张三","北京海淀区"),("李四","北京海淀区"), ("王五","北京海淀区")) 12 try: 13 cursor.executemany(sql, values) 14 except Exception,e: 15 print (e) 16 sql = "select * from address" 17 cursor.execute(sql) 18 data = cursor.fetchall() 19 if data: 20 for x in data: 21 print (x[0],x[1]) 22 cursor.close() 23 conn.close()
10.2 使用Python的持久化模块读写数据
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 import shelve 2 addresses = shelve.open('addresses') 3 addresses['1'] = ['TOM', 'Beijing road', '2008-01-03'] 4 addresses['2'] = ['Jerry', 'Shanghai road','2008-03-03'] 5 if addresses.has_key('2'): 6 del addresses['2'] 7 print (addresses) 8 addresses.close()
10.3 嵌入式数据库SQLite
10.3.1 SQLite的命令行工具
10.3.2 使用sqlite3模块访问SQLite数据库
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 import sqlite3 2 # 连接数据库 3 conn = sqlite3.connect("D:\Python\21天学通Python") 4 # 创建表 5 conn.execute("create table if not exists address(id integer primary key autoincrement,name varchar(128),address varchar(128))") 6 # 插入数据 7 conn.execute("insert into address(name, address) values('Tom','Beijing road')") 8 conn.execute("insert into address(name, address) values('Jerry','Shanghai road')") 9 # 手动提交数据 10 conn.commit() 11 # 获取游标对象 12 cur = conn.execute() 13 # 使用游标查询数据 14 cur.execute("select * from address") 15 # 获取所有结果 16 res = cur.fetchall() 17 print ("address:", res) 18 for line in res: 19 for f in line: 20 print (f,) 21 print () 22 # 关闭连接 23 cur.close() 24 conn.close()
10.5 习题
1) 根据自己的需求,练习相应的使用Python连接数据库进行操作的方法。
2) 创建一个Access数据库,然后练习使用Python读取出里面的数据。