操作数据库:
>>> import sqlite3
# 如果文件不存在,会主动在当前目录创立:
>>> conn = sqlite3.connect('test.db')
>>> cursor = conn.cursor()
>>> cursor.execute('create table user (id varchar(20) primary key, name varchar(20))')
>>> cursor.execute(r'insert into user (id, name) values (\'1\', \'Michael\')')
# 执行 insert,update,delete 语句时, 通过 rowcount 取得影响的行数:
>>> cursor.rowcount
1
>>> cursor.close()
>>> conn.commit()
>>> conn.close()
执行查问:
>>> conn = sqlite3.connect('test.db')
>>> cursor = conn.cursor()
>>> cursor.execute('select * from user where id=?', ('1',))
>>> values = cursor.fetchall()
# 后果集是一个 list,每个元素都是一个 tuple,对应一行记录
>>> values
[('1', 'Michael')]
>>> cursor.close()
>>> conn.close()