import sqlite3
# connection = sqlite3.connect(‘:memory:‘) # 在内存打开一个数据库
# 当一个数据库被多个连接访问的时候,如果其中一个进程修改这个数据库,在这个事务提交之前,这个 SQLite 数据库将会被一直锁定。timeout 参数指定了这个连接等待锁释放的超时时间,超时之后会引发一个异常。这个超时时间默认是 5.0(5秒)。
con = sqlite3.connect(‘example.db‘)
# ======= 返回字典
#def dict_factory(cursor, row):
# d = {}
# for idx, col in enumerate(cursor.description):
# d[col[0]] = row[idx]
# return d
#con.row_factory = dict_factory
# ======= 方法二
con.row_factory = sqlite3.Row
# 获取游标
cur = con.cursor()
# Create table
cur.execute(‘‘‘CREATE TABLE student (name TEXT, age TEXT, sex INTEGER);‘‘‘)
# 插入数据
cur.execute("INSERT INTO student VALUES (‘iFan‘, 18, 1)")
# 提交
con.commit()
# 查询
s = (‘iFan‘,)
cur.execute(‘SELECT * FROM student WHERE name=?‘, s)
# 返回的是sqlite3.Row对象,看使用的row_factory方法
# 转为字典
print({k: student[k] for k in student.keys()})
# 修改
cur.execute("UPDATE student SET name=‘iFan2‘ WHERE name=‘name2‘")
print(cur.rowcount)
# 删除
cur.execute("DELETE FROM student where name = ‘name1‘")
print(cur.rowcount)
# 批量插入
students = [(‘name%s‘ % i, 18 + i, 0 if i % 2 == 0 else 1) for i in range(10)]
cur.executemany(‘INSERT INTO student(name, age, sex) VALUES (?,?,?)‘, students)
students = [{"name": "name%s" % i, "age": i, "sex": 0 if i % 2 == 0 else 1} for i in range(10)]
cur.executemany("INSERT INTO student (name, age, sex) VALUES (:name, :age, :sex)", students)
# 查看插入的条数
print(cur.rowcount)
# 查看最后插入的自增的id
print(cur.lastrowid)
con.commit()
# con.rollback() # 回滚
cur.close()
# 关闭连接
con.close()
原文:https://www.cnblogs.com/iFanLiwei/p/12865637.html