SQLite 是内嵌在 Python 中的轻量级、基于磁盘文件的数据库管理系统,不需要服务器进程,支持使用 SQL 语句来访问数据库。
首先创建一个与数据库关联的 Connection 对象。
>>> import sqlite3
>>> con = sqlite3.connect('example.db')
再创建一个 Cursor 对象,并调用该对象的 execute() 方法来执行 SQL 语句。
>>> c = con.cursor()
>>> c.execute("CREATE TABLE stocks (date text, trans text, symbol text, qty real, price real)") # 创建表
<sqlite3.Cursor object at 0x03462660>
>>> c.execute("INSERT INTO stocks VALUES ('2006-01-05', 'BUY', 'RHAT', 100, 35.14)") # 插入记录
<sqlite3.Cursor object at 0x03462660>
>>> con.commit() # 提交事务,保存数据
>>> con.close() # 关闭数据库连接
查询表中的数据,需要重新创建 Connection 对象和 Cursor 对象,再使用下面代码:
>>> for row in c.execute('SELECT * FROM stocks ORDER BY price'):
print(row)
('2006-01-05', 'BUY', 'RHAT', 100.0, 35.14)
14.1.1 Connection 对象
35E8014050BDE9B14E31962DB19212E6.jpg
下面代码演示如何在 sqlite3 连接中创建并调用自定义函数:
import sqlite3
import hashlib
def md5sum(t):
return hashlib.md5(t).hexdigest()
con = sqlite3.connect(":memory:")
con.create_function("md5", 1, md5sum) # 创建可在 SQL 语句中调用的函数,"md5" 为函数名,1为参数个数,md5sum 表示可调用对象
cur = con.cursor()
cur.execute("select md5(?)", (b"foo",)) # 在 SQL 语句中调用自定义函数
print(cur.fetchone()[0])
14.1.2 Cursor 对象
(1)execute(sql[,parameters])
import sqlite3
con = sqlite3.connect(":memory:")
cur = con.cursor()
cur.execute("create table people (name_last, age)")
who = "Dong"
age = 38
# 使用问好作为占位符
cur.execute("insert into people values (?, ?)", (who, age))
# 使用命名变量作为占位符
cur.execute("select * from people where name_last=:who and age=:age", {"who":who, "age":age})
print(cur.fetchone())
(2)executemany(sql,seq_of_parameters)
该方法用来对给定参数执行同一个 SQL 语句,该参数序列可以使用不同的方式产生。如,下面的代码使用序列作为 SQL 语句的参数:
import sqlite3
persons = [("Hugo", "Boss"), ("Calvin", "Klein")]
con = sqlite3.connect(":memory:")
# 创建表
con.execute("create table person(firstname, lastname)")
# 插入数据
con.executemany("insert into person(firstname, lastname) values (?, ?)", persons)
# 显示数据
for row in con.execute("select firstname, lastname from person"):
print(row)
print("I just deleted", con.execute("delete from person").rowcount, "rows")
(3)fetchone()、fetchmany(size = cursor.arraysize)、fetchall()
这三个方法用来读取数据。假设数据库通过下面的方法创建并插入数据:
import sqlite3
conn = sqlite3.connect("D://Python//addressBook.db")
cur = conn.cursor()
cur.execute("CREATE TABLE addressList (name text, sex text, phone text, QQ text, address text)")
cur.execute('''insert into addressList(name, sex, phone, QQ, address) values
('王小丫', '女', '13888991234', '341245245', '北京市')''')
conn.commit()
conn.close()
则下面代码演示了 fetchall() 读取数据的方法:
import sqlite3
conn = sqlite3.connect(r'D:/Python/addressBook.db')
cur = conn.cursor()
cur.execute('select * from addressList')
li = cur.fetchall()
for line in li:
for item in line:
if type(item) != str:
s = str(item)
else:
s = item
print(s + '\t', end = ' ')
print()
conn.close()
14.1.3 Row 对象
import sqlite3
con = sqlite3.connect('example.db')
con.row_factory = sqlite3.Row
c = con.cursor()
c.execute('select * from stocks')
r = c.fetchone()
print(type(r))
print(tuple(r))
print(len(r))
print(r[2])
print(r.keys())
print(r['qty'])
for member in r:
print(member)
运行结果:
<class 'sqlite3.Row'>
('2006-01-05', 'BUY', 'RHAT', 100.0, 35.14)
5
RHAT
['date', 'trans', 'symbol', 'qty', 'price']
100.0
2006-01-05
BUY
RHAT
100.0
35.14
14.2.3 操作 MySQL 数据库
可使用 MySQLdb 模块访问 MySQL 数据库。
使用该模块查询 MySQL 数据库记录的方法:
import MySQLdb
try:
conn = MySQLdb.connect(host = 'localhost', user = 'root', password = '88888888',db = 'student',
port = 3306)
cur = conn.cursor()
cur.execute('select * from users')
cur.close()
conn.close()
except MySQLdb.Error as e:
print("Mysql Error %d: %s"%(e.args[0], e.args[1]))
插入用法:
import MySQLdb
try:
conn = MySQLdb.connect(host = 'localhost', user = 'root', password = '88888888',db = 'student',
port = 3306)
cur = conn.cursor()
cur.execute('create database if not exists python')
conn.select_db('python')
cur.execute('create table test(id int, info varchar(20))') # 执行单条 SQL 语句
value = [1, 'hi rollen']
cur.execute('insert into test values(%s, %s)', value)
values = []
for i in range(20):
values.append((i, 'hi rollen' + str(i)))
cur.executemany('insert into test values(%s, %s)', values)
cur.execute('update test set info = "I am rollen" where id = 3') # 执行多条 SQL 语句
conn.commit() # 提交事务
cur.close()
conn.close()
except MySQLdb.Error as e:
print("MySQL Error %d: %s"%(e.args[0], e.args[1]))