参考文档
操作总结
准备工作,引用包,并建立连接
import sqlite3 db_conn = sqlite3.connect('example.db')
建表
db_conn.execute(r''' CREATE TABLE stocks ( uuid text,date text,trans text,symbol text,qty real,pricereal ) ''')
也可以判断表是否存在,如果不存在就新建
db_conn.execute(r''' CREATE TABLE IF NOT EXISTS stocks ( uuid text,pricereal ) ''')
插入数据
普通方式
组装原始sql语句进行插入,这种使用字符串拼接的方法不安全,可能会被sql注入
db_conn.execute(r''' INSERT INTO stocks VALUES ('2001-01-11','BUY','RHAT',100,35.14) ''') db_conn.commit()
参数绑定方式
数字方式,第二个参数必须是一个tuple,冒号后面加数字作为占位符
db_conn.execute(r''' INSERT INTO stocks VALUES (:1,:2,:3,:4,:5) ''',('2001-01-11',35.14) ) db_conn.commit()
问号方式,第二个参数必须是一个tuple
db_conn.execute(r''' INSERT INTO stocks VALUES (:1,35.14) ) db_conn.commit()
命名方式, 第二个参数可以是一个tuple或者是dict
db_conn.execute(r''' INSERT INTO stocks VALUES (:aa,:bb,:cc,:dd,:ee) ''',35.14) ) db_conn.execute(r'''INSERT INTO stocks VALUES (:aa,{'aa': '2001-01-11','bb': 'BUY','cc': 'RHAT','dd':100,'ee': 35.14} ) db_conn.execute(r'''INSERT INTO stocks (date,trans,symbol,qty,price) VALUES (:aa,'ee': 35.14} ) db_conn.commit()
这三种方式就和字符串的format的用法差不多
executemany
插入多条数据
可以把问号替换成上面讲的其他占位符号
purchases = [('2006-03-28','IBM',1000,45.00),('2006-04-05','MSFT',72.00),('2006-04-06','SELL',500,53.00),] db_conn.executemany(r''' INSERT INTO stocks VALUES (?,?,?) ''',purchases) db_conn.commit()
查询数据
fetchone 查询单条数据 fetchall 查询所有数据 fetchmany 查询指定数目的数据 它们的返回结果是tuple或者tuple数组,如果没有数据就返回None
for row in c.execute('SELECT * FROM stocks ORDER BY price'): print(row)
游标使用
提交与回滚操作必须还是由db_conn
来进行处理
import sqlite3 db_conn = sqlite3.connect('example.db') db_cur = db_conn.cursor() #使用游标建表 db_cur.execute(r''' CREATE TABLE IF NOT EXISTS stocks (date text,price real) ''') #使用游标插入数据 db_cur.execute("INSERT INTO stocks VALUES ('2006-01-05',35.14)") #数据库连接进行提交操作 db_conn.commit() db_conn.close()
其他说明
executescript
一次性执行多句sql
db_conn.executescript(r''' create table person( firstname,lastname,age ); create table book( title,author,published ); insert into book(title,published) values ( 'Dirk Gently''s Holistic Detective Agency','Douglas Adams',1987 ); ''')
结合上下文协议管理来连接的关闭with
的使用
db_conn = sqlite3.connect(":memory:") db_conn.execute("create table person (id integer primary key,firstname varchar unique)") # 将会在with语句结束后自动调用db_conn.commit()来进行提交 with db_conn: db_conn.execute("insert into person(firstname) values (?)",("Joe",)) # 在抛异常时将会自动调用db_conn.rollback()来进行回滚,但是异常仍然会被抛出 try: with db_conn: db_conn.execute("insert into person(firstname) values (?)",)) except sqlite3.IntegrityError: print("couldn't add Joe twice")原文链接:https://www.f2er.com/sqlite/198241.html