43 - 操作SQLite数据

网友投稿 717 2022-11-02

43 - 操作SQLite数据库

43 - 操作SQLite数据库

​​1. 如何创建SQLite数据库​​​​2. 如何向SQLite表中插入数据​​​​3. 如何查询SQLite表中的数据​​

1. 如何创建SQLite数据库

# 1. create database and table'''sqlite3内置模块,不需要安装'''import sqlite3import osdbPath = 'data.sqlite'if not os.path.exists(dbPath): conn = sqlite3.connect(dbPath) c = conn.cursor() c.execute('''create table persons (id int primary key not null, name text not null, age int not null, address char(100), salary real);''') conn.commit() conn.close() print('创建数据库成功')

创建数据库成功

2. 如何向SQLite表中插入数据

# 2. insertconn = sqlite3.connect(dbPath)c = conn.cursor()c.execute('delete from persons')c.execute(''' insert into persons(id, name, age, address, salary) values(1, 'Bill', 32, 'Colifornia', 20000);''')c.execute(''' insert into persons(id, name, age, address, salary) values(2, 'Mike', 30, 'China', 10000);''')c.execute(''' insert into persons(id, name, age, address, salary) values(3, 'Jhon', 12, 'Norway', 30000);''')conn.commit()print('insert success')

insert success

3. 如何查询SQLite表中的数据

# 3. selectpersons = c.execute('select name, age, address, salary from persons order by age')print(type(persons))result = []for person in persons: value = {} value['name'] = person[0] value['age'] = person[1] value['address'] = person[2] result.append(value)conn.close()print(type(result))print(result)import jsonresultStr = json.dumps(result)print(resultStr)

[{'name': 'Jhon', 'age': 12, 'address': 'Norway'}, {'name': 'Mike', 'age': 30, 'address': 'China'}, {'name': 'Bill', 'age': 32, 'address': 'Colifornia'}][{"name": "Jhon", "age": 12, "address": "Norway"}, {"name": "Mike", "age": 30, "address": "China"}, {"name": "Bill", "age": 32, "address": "Colifornia"}]

​​44 - 操作MySQL数据库​​

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:Finn是一个快速和简单的框架采用Go语言实现Raft
下一篇:Swift编写的iOS端和服务器端, 服务器端基于Perfect框架
相关文章

 发表评论

暂时没有评论,来抢沙发吧~