python 之 使用SQLite
2016-03-24 17:11
603 查看
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:…
相关文章推荐
- Android之获取手机上的图片和视频缩略图thumbnails
- Python动态类型的学习---引用的理解
- Python3写爬虫(四)多线程实现数据爬取
- 垃圾邮件过滤器 python简单实现
- 下载并遍历 names.txt 文件,输出长度最长的回文人名。
- install and upgrade scrapy
- Scrapy的架构介绍
- Centos6 编译安装Python
- 使用Python生成Excel格式的图片
- 让Python文件也可以当bat文件运行
- [Python]推算数独
- Python中zip()函数用法举例
- Python中map()函数浅析
- 数据库链接字符串查询网站
- Python将excel导入到mysql中
- Python在CAM软件Genesis2000中的应用
- 使用Shiboken为C++和Qt库创建Python绑定