sqlite结合python_SQLite在python3中的应用

本文介绍了如何使用Python的sqlite3模块连接SQLite数据库,创建user表并插入数据,进行查询、修改和删除操作。遇到的问题是PyCharm中数据库设置为只读,而在sqlitestudio中则正常。主要涉及SQL语句和Python数据库操作。
摘要由CSDN通过智能技术生成

创建/连接数据库

import sqlite3

conn = sqlite3.connect('example.db')

cursor = conn.cursor()

建立一张叫user的表

cursor.execute('create table user(id varchar(20) primary key, name verchar(20), password verchar(20), rights int)')

插入行

cursor.execute(r"insert into user values ('A00001', 'Adam', 'A00001', 0)")

cursor.execute(r"insert into user values ('A00002', 'Bart', 'A00002', 2)")

cursor.execute(r"insert into user values ('A00003', 'Lisa', 'A00003', 1)")

mess = [a, b, c, d]

cursor.execute(r"insert into user values (?, ?, ?, ?)", mess)

查询

t = cursor.execute('select * from user where user.name!="Lisa"')

for row in t:

print(row)

# 输出:

# ('A00001', 'Adam', 'A00001', 0)

# ('A00002', 'Bart', 'A00002', 2)

修改了表之后要commit

conn.commit()

做完了你要做的要close

cursor.close()

conn.close()

修改数据

cursor.execute("update user set name=? where id=?", ('Maya', id))

删除一行

cursor.execute('delete from user where id=?', id)

更新表

cursor.execute("alter table table_name add clum type")

说明:ALTER TABLE和SQLite SQLite对使用ALTER TABLE执行的操作有所限制。最重要的一个限制是,它不支持使用ALTER TABLE定义主键和外键,这些必须在最初创建表 时指定。

通配符

最常使用的通配符是百分号(%)。在搜索串中,%表示任何字符出现任意次数。

cursor.execute("select * from user where name like 'H%'")

cursor.execute("select * from doc where name like ? and new=1", (name, ))

我用pycharm建的数据库不知道为什么是只读的,用sqlitestudio建的就没什么问题。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值