python 之 使用SQLite

SQLite

SQLite是一种嵌入式数据库,它的数据库就是一个文件。由于SQLite本身是C写的,而且体积很小,所以,经常被集成到各种应用程序中,甚至在iOS和Android的App中都可以集成。

Python就内置了SQLite3,所以,在Python中使用SQLite,不需要安装任何东西,直接使用。

在使用SQLite前,我们先要搞清楚几个概念:

表是数据库中存放关系数据的集合,一个数据库里面通常都包含多个表,比如学生的表,班级的表,学校的表,等等。表和表之间通过外键关联。

要操作关系数据库,首先需要连接到数据库,一个数据库连接称为Connection;

连接到数据库后,需要打开游标,称之为Cursor,通过Cursor执行SQL语句,然后,获得执行结果。

Python定义了一套操作数据库的API接口,任何数据库要连接到Python,只需要提供符合Python标准的数据库驱动即可。

由于SQLite的驱动内置在Python标准库中,所以我们可以直接来操作SQLite数据库。

sqlite_test.py

# 导入SQLite驱动
import sqlite3
# 链接到数据库,数据库文件就是 test.db
# 如果文件不存在,会自动在当前目录创建
conn = sqlite3.connect('test.db')
# 创建一个cursor
cursor = conn.cursor()
# 执行一条SQL语句,创建user表
cursor.execute('create table user (id varchar(20) primary key,name varchar(20))')
# 插入一条记录
cursor.execute('insert into user (id,name) values (\'1\',\'Michael\')')
# 通过rowcount获取插入的行数
print(cursor.rowcount) # 1
# 关闭cursor
cursor.close()
# 提交事务
conn.commit()
# 关闭connection
conn.close()

sqlite_test1.py

# 查询记录
import sqlite3
conn = sqlite3.connect('test.db')
cursor = conn.cursor()
cursor.execute('select * from user where id=?','1')
values = cursor.fetchall()
print(values) # [('1', 'Michael')]
cursor.close()
conn.close()

练习

根据分数段查找指定的名字

# -*- coding:utf-8 -*-
import os,sqlite3

db_file = os.path.join(os.path.dirname(__file__),'test.db')
if os.path.isfile(db_file): # 如果db_file是一个文件而不是目录
    os.remove(db_file)

# 初始数据
conn = sqlite3.connect(db_file)
cursor = conn.cursor()
cursor.execute('create table user (id varchar(20) primary key,name varchar(20),score int)')
cursor.execute(r"insert into user values ('A-001','Adam',95)")
cursor.execute(r"insert into user values ('A-002','Bart',67)")
cursor.execute(r"insert into user values ('A-003','Lisa',78)")

cursor.close()
conn.commit()
conn.close()

def get_score_in(low,high):
    try:
        conn = sqlite3.connect(db_file)
        cursor = conn.cursor()
        cursor.execute('select name from user where score between ? and ? order by score asc',(low,high))
        rs = cursor.fetchall()
    finally:
        cursor.close()
        conn.close()
    return list(map(lambda x:x[0],rs))

assert get_score_in(80,96) == ['Adam'],print(get_score_in(80,96))
assert get_score_in(60,80) == ['Bart','Lisa'],print(get_score_in(60,80))
assert get_score_in(60,100) == ['Bart','Lisa','Adam'],print(get_score_in(60,100))
print('pass')

总结

在Python中操作数据库时,要先导入数据库对应的驱动,然后,通过Connection对象和Cursor对象操作数据。

要确保打开的Connection对象和Cursor对象都正确地被关闭,否则,资源就会泄露。

确保出错的情况下也关闭掉Connection对象和Cursor对象的方法:try:…except:…finally:…

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值