SQLite是一种嵌入式数据库,它的数据库就是一个文件。由于SQLite本身是C写的,而且体积很小,所以,经常被集成到各种应用程序中。
Python就内置了SQLite3,所以,在Python中使用SQLite,不需要安装任何东西,直接使用。
要操作关系数据库,首先需要连接到数据库,一个数据库连接称为Connection;
连接到数据库后,需要打开游标,称之为Cursor,通过Cursor执行SQL语句。
Python定义了一套操作数据库的API接口,任何数据库要连接到Python,只需要提供符合Python标准的数据库驱动即可。
# 导入SQLite驱动:
import sqlite3
# 连接到SQLite数据库,数据库文件是test.db,如果文件不存在,会自动在当前目录创建
conn = sqlite3.connect('test.db')
# 创建一个游标Cursor:
cursor = conn.cursor()
#执行一条SQL语句,创建user表:
cursor.execute('create table user (name text, age integer)')
SQLite中每个表都默认包含一个隐藏列rowid。通常情况下,rowid可以唯一的标记表中的每个记录。表中插入的第一个条记录的rowid为1,后续插入的记录的rowid依次递增1。即使插入失败,rowid也会被加1。所以,整个表中的rowid并不一定连续,即使用户没有删除过记录。
由于唯一性,所以rowid在很多场合中当作主键使用。在使用的时候,select * from tablename 并不能获取rowid,必须显式的指定。例如,select rowid, * from tablename 才可以获取rowid列。
表中字段类型可以是:
integer:整形
txet:文本型
real:实数(浮点型)
blob:逻辑型
sqlite3支持建立自增主键,方法是 字段类型integer 附加 primary key autoincrement。
cursor.execute('create table user (id integer primary key autoincrement, name text)')
sqlite3在创建表时先判断表是否存在,然后再创建新表:
cursor.execute('create table if not exists user (id integer primary key autoincrement, name text)')
#继续执行一条SQL语句,插入一条记录:
cursor.execute('insert into user (name, age) values ("Jack", 19)')
#查询记录
cursor.execute('select * from user where name=?t', ("Jack",))
# 输出下一条符合条件的记录
print(cursor.fetchone())
# 输出所有符合条件的记录
print(cursor.fetchall())
# 关闭Cursor:
cursor.close()
# 提交事务:
conn.commit()
#关闭Connection:
conn.close()