python-简单的sqlite3使用
1 # 导入SQLite驱动: 2 >>> import sqlite3 3 # 连接到SQLite数据库 4 # 数据库文件是test.db 5 # 如果文件不存在,会自动在当前目录创建: 6 >>> conn = sqlite3.connect('test.db') 7 # 创建一个Cursor: 8 >>> cursor = conn.cursor() 9 # 执行一条SQL语句,创建user表: 10 >>> cursor.execute('create table user (id varchar(20) primary key, name varchar(20))') 11 <sqlite3.Cursor object at 0x10f8aa260> 12 # 继续执行一条SQL语句,插入一条记录: 13 >>> cursor.execute('insert into user (id, name) values (\'1\', \'Michael\')') 14 <sqlite3.Cursor object at 0x10f8aa260> 15 # 通过rowcount获得插入的行数: 16 >>> cursor.rowcount 17 1 18 # 关闭Cursor: 19 >>> cursor.close() 20 # 提交事务: 21 >>> conn.commit() 22 # 关闭Connection: 23 >>> conn.close() 24 25 26 27 >>> conn = sqlite3.connect('test.db') 28 >>> cursor = conn.cursor() 29 # 执行查询语句: 30 >>> cursor.execute('select * from user where id=?', ('1',)) 31 <sqlite3.Cursor object at 0x10f8aa340> 32 # 获得查询结果集: 33 >>> values = cursor.fetchall() 34 >>> values 35 [('1', 'Michael')] 36 >>> cursor.close() 37 >>> conn.close()