Python: sqlite3模块

sqlite3 --- SQLite 数据库 DB-API 2.0 接口模块

SQLite 是一个C语言库,它可以提供一种轻量级的基于磁盘的数据库,这种数据库不需要独立的服务器进程,也允许需要使用一种非标准的 SQL 查询语言来访问它。一些应用程序可以使用 SQLite 作为内部数据存储。可以用它来创建一个应用程序原型,然后再迁移到更大的数据库,比如 PostgreSQL 或 Oracle。

参见

https://github.com/ghaering/pysqlite

pysqlite的主页 -- sqlite3 在外部使用 “pysqlite” 名字进行开发。

https://www.sqlite.org

SQLite的主页;它的文档详细描述了它所支持的 SQL 方言的语法和可用的数据类型。

https://www.w3schools.com/sql/

学习 SQL 语法的教程、参考和例子。

例子

创建一个text.db数据库,然后创建和插入,定义查找方法,最后使用assert进行测试。

import os, sqlite3
# 当前脚本执行的目录名称。os.path是一个操作路径的模块
print(os.path.dirname(__file__))
# 连接成一个路径
db_file = os.path.join(os.path.dirname(__file__), 'test.db')
# 判断当前目录是否存在这个文件,如果存在则移除。直接删除了,不会到回收站。
if os.path.isfile(db_file):
    os.remove(db_file)

# 连接或创建数据库
conn = sqlite3.connect(db_file)
# 创建操作数据库的光标对象
cursor = conn.cursor()
cursor.execute('create table user(id varchar(20) primary key, name varchar(20), score int)')
cursor.execute(r'insert into user values("A-001", "Adam", 95)')
cursor.execute(r"insert into user values ('A-002', 'Bart', 62)")
cursor.execute(r"insert into user values ('A-003', 'Lisa', 78)")
conn.commit()
cursor.close()
conn.close()

def get_score_in(low, high):
    try:
        conn = sqlite3.connect(db_file)
        cursor = conn.cursor()
        cursor.execute('select name from user where score between ? and ? order by score asc', (low, high) )
        result = cursor.fetchall()
        # 使用list comprehension
        return [ item[0] for item in result]
    except Exception as e:
        print("Error:" , e)
        return []
    finally:
        cursor.close()
        conn.close()

assert get_score_in(80, 95) == ['Adam'], get_score_in(80, 95)
assert get_score_in(60, 80) == ['Bart', 'Lisa'], get_score_in(60, 80)
assert get_score_in(60, 100) == ['Bart', 'Lisa', 'Adam'], get_score_in(60, 100)

print("Pass")

猜你喜欢

转载自www.cnblogs.com/chentianwei/p/11939891.html