您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

python 操作Sqlite3

bubuko 2022/1/25 19:51:07 python 字数 1894 阅读 1004 来源 http://www.bubuko.com/infolist-5-1.html

```pythonimport sqlite3# connection = sqlite3.connect(':memory:') # 在内存打开一个数据库# 当一个数据库被多个连接访问的时候,如果其中一个进程修改这个数据库,在这个事务提交之前,这个 SQLite 数据库将会被一直锁定。timeou... ...
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()

python 操作Sqlite3

原文:https://www.cnblogs.com/iFanLiwei/p/12865637.html


如果您也喜欢它,动动您的小指点个赞吧

除非注明,文章均由 laddyq.com 整理发布,欢迎转载。

转载请注明:
链接:http://laddyq.com
来源:laddyq.com
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。


联系我
置顶