Python每日一练——数据存储第五关:操作SQLite数据库

面试题第五关:

第一部分——考点:

操作SQLite数据库:

  1. 创建SQLite数据库;
  2. 向表中插入记录;
  3. 其他数据库操作。

第二部分——面试题:

1.面试题一:如何创建SQLite数据库?

2.面试题二:如何向SQLite表中插入数据?

3.面试题三:如何查询SQLite表中的数据?


第三部分——解析:

面试题一 之 创建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('创建数据库成功')

在这里插入图片描述

  • 我们通过上述操作已经成功创建了sql数据库,并在里面创建了一张表。

  • 为了查看我们创建的表,我们可以用到SqliteStudio,它是一款 Sqlite数据库可视化工具,是使用Sqlite数据库开发应用的必备软件,软件无需安装,下载后解压即可使用,很小巧但很了用,绿色中文版本。比起其它SQLite管理工具,我喜欢用这个。很方便易用,不用安装的单个可执行文件,支持中文。

  • 官方下载地址:这里

  • 可能会下载不了,所以我这边已经下载一个(3.3.3版本),微信公众号【孤寒者】后台回复【sqlitestudio】即可~

在这里插入图片描述

面试题二 之 向SQLite表中插入数据:

# coding=utf-8
# _author__ = 孤寒者
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')

在这里插入图片描述

在这里插入图片描述

面试题三 之 查询SQLite表中的数据:

# coding=utf-8
# _author__ = 孤寒者
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)

在这里插入图片描述

扫描二维码关注公众号,回复: 13819743 查看本文章

第四部分——总结:

  • 使用sqlite3模块中的API可以操作SQLite数据库,该模块是Python内置的模块,不需要单独安装。

  • 如果想要系统学习SQLite数据库,可以观看菜鸟教程学习:
    菜鸟教程:SQLite教程

猜你喜欢

转载自blog.csdn.net/qq_44907926/article/details/123019175
今日推荐