# 执行一个sql语句,创建一个表 sql = 'CREATE TABLE if not exists user (id varchar(20) primary key AUTOINCREMENT, name varchar(20), age integer)' cursor.execute(sql) # 增删改必须调用commit才能生效 conn.commit()
# 插入一条记录 sql = 'INSERT INTO user (name, age) values (\'bomo\', 18)' cursor.execute(sql) conn.commit()
# 删除一条记录 sql = 'DELETE FROM user WHERE name=\'bomo\'' cursor.execute(sql) conn.commit()
# 查询多行 cu.execute('select * from user limit 1') rows = cu.fetchall() for row in rows: # print type(row) # <type 'sqlite3.Row'> # 取得所有的列 for col in row.keys(): print'%s=%s ' % (col, i[col]) # 输出: # id=1 # name=bomo # age=18
# 查询单行 cu = connection.cursor() cu.execute('select count(*) as rowcount count from user') row = cu.fetchone() for col in row.keys(): print'%s=%s ' % (col, i[col]) # 输出: # rowcount=2
cu.close() connection.close()
当然,我们也可以自定义row_factory
1 2 3 4 5 6 7 8
# 自定义row构造器,返回字典对象,可以通过列名索引 defdict_factory(cursor, row): d = {} for idx, col inenumerate(cursor.description): d[col[0]] = row[idx] return d