Python之SQLite数据库怎么创建

发布时间:2022-06-13 13:45:32 作者:iii
来源:亿速云 阅读:1039

这篇文章主要讲解了“Python之SQLite数据库怎么创建”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“Python之SQLite数据库怎么创建”吧!

1.创建SQLite数据库

# coding=utf-8
# _author__ = 孤寒者
import sqlite3
import os
dbPath = '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('创建数据库成功')

Python之SQLite数据库怎么创建

Python之SQLite数据库怎么创建

2.向SQLite表中插入数据

# coding=utf-8
import sqlite3
dbPath = 'data.sqlite'
conn = sqlite3.connect(dbPath)
c = conn.cursor()
# 首先将表中数据全部删除
c.execute('delete from persons')
# 插入数据
c.execute('''
insert into persons(id,name,age,address,salary)
values(1, '孤寒者', 18, 'China', 9999)
''')
c.execute('''
insert into persons(id,name,age,address,salary)
values(2, '小张', 55, 'China', 9)
''')
conn.commit()
print('insert success')

Python之SQLite数据库怎么创建

Python之SQLite数据库怎么创建

3.查询SQLite表中的数据

# coding=utf-8
import sqlite3
dbPath = 'data.sqlite'
conn = sqlite3.connect(dbPath)
c = conn.cursor()
persons = c.execute('select name,age,address,salary from persons order by age')

# 打印查询结果发现是个Cursor对象(可迭代对象)
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)

# 我们也可以使用前面学习的json模块使这个list类型的result转为字符串类型
# 网络传输需要使用字符串类型
import json
resultStr = json.dumps(result, ensure_ascii=False)
print(resultStr)

Python之SQLite数据库怎么创建

感谢各位的阅读,以上就是“Python之SQLite数据库怎么创建”的内容了,经过本文的学习后,相信大家对Python之SQLite数据库怎么创建这一问题有了更深刻的体会,具体使用情况还需要大家实践验证。这里是亿速云,小编将为大家推送更多相关知识点的文章,欢迎关注!

推荐阅读:
  1. Andorid Sqlite数据库的创建
  2. 怎么在Python中操作SQLite数据库

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

python sqlite

上一篇:java如何实现日历窗口小程序

下一篇:如何利用JavaScript构建树形图

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》