現有的資料庫管理系統有很多種,本文選擇介紹兩種DBMS:SQLite 3 和 Mysql。
SQLite 3
SQLite 3是Python 3預裝的、相當完備、無需配置的基于SQL的資料庫管理系統。要使用SQLite,隻需導入sqlite3庫,并使用Python标準化資料庫API來程式設計,而不用處理其他工作,比如:安裝資料庫、配置等等。
Python資料庫API 提供了一種标準機制,可以針各種各樣的資料庫管理系統,包括SQLite。不管使用什麼背景資料庫,代碼所遵循的過程都是一樣的:連接配接 -> 建立遊标 -> 互動(利用遊标,使用SQL管理資料)->送出/復原 ->關閉
示例1:
#導入你需要的庫
importsqlite3#1、建立與資料庫的連接配接
connection=sqlite3.connect('test.db');#2、建立資料遊标
cursor=connection.cursor()#3、執行一些SQL操作
cursor.execute("""select date('NOW')""")print(cursor.fetchone())#4、送出所做的修改,使修改永久保留
connection.commit()#5、完成時關閉連結
connection.close()
輸出:
('2013-06-26',)
示例2:
建立資料庫 -> 插入資料 -> 查詢
importsqlite3
db='test.sqlite' #資料庫名
drop_table_sql="drop table if exists books;"create_table_sql="""create table books(
id integer primary key autoincrement unique not null,
name text not null,
price integer,
publish_date date not null
);"""connection=sqlite3.connect(db)
cursor=connection.cursor()#建立資料庫
cursor.execute(drop_table_sql)
cursor.execute(create_table_sql)#插入資料
insert_sql="insert into books (name,price,publish_date) values (?,?,?)"#? 為占位符
cursor.execute(insert_sql,('java',123.23,'2012-12-03'))
cursor.execute(insert_sql,('C++',83.23,'2013-02-03'))
connection.commit()#查詢
select_sql = "SELECT * FROM books"cursor.execute(select_sql)#傳回一個list,list中的對象類型為tuple(元組)
data=cursor.fetchall()for t indata:print(t)
connection.close()
輸出:
(1, 'java', 123.23, '2012-12-03')
(2, 'C++', 83.23, '2013-02-03')
Mysql
Mysql是非常流行的開源關系性資料庫。
要使用Python通路Mysql,需要一個連接配接庫,即對Python DB API的一個實作,相當于JAVA中的MySQL的JDBC Driver。其中比較著名就是MySQLdb(Django項目使用它),不過,目前MySQLdb并不支援python3.x。我們隻能采用其他連接配接庫,MySQL官方已經提供了MySQL連接配接器,而且已經有支援Python3.x的版本了。
MySQL Connector/Python enables Python programs to access MySQL databases, using an API that is compliant with the Python DB API version 2.0。
關于MySQL Connector/Python的各種介紹、安裝、API等文檔,請參考官網:http://dev.mysql.com/doc/connector-python/en/index.html
示例:
importmysql.connectorimportsys, os
user= 'root'pwd= '123456'host= '127.0.0.1'db= 'test'connection= mysql.connector.connect(user=user, password=pwd, host=host, database=db)
cursor=connection.cursor()#建立資料庫表
drop_table_sql="drop table if exists person;"create_table_sql= """CREATE TABLE person(
id int(10) AUTO_INCREMENT PRIMARY KEY,
name varchar(20),
age int(4)
)CHARACTER SET utf8;"""
try:
cursor.execute(drop_table_sql)
cursor.execute(create_table_sql)exceptmysql.connector.Error as err:print("create table 'mytable' failed.")print("Error: {}".format(err.msg))
sys.exit()#插入資料
insert_sql = 'INSERT INTO person(name, age) VALUES (%s,%s)'
try:
cursor.execute(insert_sql,('Jay', 22))
cursor.execute(insert_sql,('Tony', 26))
cursor.execute(insert_sql,('邵',24))exceptmysql.connector.Error as err:print("insert table 'mytable' failed.")print("Error: {}".format(err.msg))
sys.exit()#查詢資料
select_sql = "SELECT * FROM person"
try:#cursor.execute() 傳回 None; 執行SQL後的資訊存儲在cursor對象内。
cursor.execute(select_sql)#擷取一條記錄,每條記錄做為一個tuple(元組)傳回
data=cursor.fetchone()print(data)#擷取2條記錄,注意由于之前執行有了fetchone(),是以遊标已經指到第二條記錄了,也就是從第二條開始的2條記錄
data=cursor.fetchmany(2)print(data)
cursor.execute(select_sql)#擷取所有結果
data=cursor.fetchall()print(data)
cursor.execute(select_sql)#擷取所有結果
for (id, name, age) incursor:print("ID:{} Name:{} Age:{}".format(id, name, age))exceptmysql.connector.Error as err:print("query table 'mytable' failed.")print("Error: {}".format(err.msg))
sys.exit()
connection.commit()
cursor.close()
connection.close()
輸出:
(1, 'Jay', 22)
[(2, 'Tony', 26), (3, '邵', 24)]
[(1, 'Jay', 22), (2, 'Tony', 26), (3, '邵', 24)]
ID:1 Name:Jay Age:22
ID:2 Name:Tony Age:26
ID:3 Name:邵 Age:24