话不多说,直接贴出使用代码
#!/usr/bin/env python3
#================================================================
# Copyright (C) 2019 Renleilei. All rights reserved.
#
# 文件名称:025_sqlite3Use
# 创 建 者:JohnnyTrueman
# 创建日期:2019年06月19日
# 描 述:
# 版 本: Version 1.00
# 参考文献: https://www.liaoxuefeng.com/wiki/1016959663602400/1017598873256736 (廖雪峰python教程中关于错误、调试和测试章节)
# https://www.liaoxuefeng.com/wiki/1016959663602400/1017801751919456 (廖雪峰python教程中关于sqlite3数据库的连接和使用)
# https://docs.python.org/3/library/exceptions.html#exception-hierarchy (python官方网站中关于 Exception 各种类的区分说明)
#================================================================
import sqlite3
import os
dbFilePath = os.path.join(os.path.dirname(__file__), 'draw.db')
# 初始化数据库文件和数据
def initData():
conn = sqlite3.connect(dbFilePath)
cursor = conn.cursor()
cursor.execute('create table drawList(rewordID varchar(20) primary key, rewordNum varchar(30))')
cursor.execute(r"insert into drawList values ('20190619', '3,\ 18,\ 25,\ 27,\ 29,\ 30,\ 3')")
cursor.close()
conn.commit()
conn.close()
print('sql test program begin......')
# 查找某一期的获奖号码序列
def find(id):
print('begin find id:', id)
conn=sqlite3.connect(dbFilePath)
cursor=conn.cursor()
"""
使用try catch来捕捉sql语句的执行结果
"""
try:
print('trying...')
cursor.execute('select rewordNum from drawList where rewordID=?', (str(id),))
except BaseException as e:
print('except...', e)
else:
print('else... no error exception occur!')
values=cursor.fetchall()
print(values)
finally:
print('finally...')
cursor.close()
conn.close()
print('try end...')
## 执行
if os.path.isfile(dbFilePath):
print(dbFilePath)
else:
initData()
find(20190619)
### 技术总结:
# -1, python集成了sqlite3数据库驱动,无需再次安装sqlite3,import之后即可直接使用
# -2, 数据库文件 test.db 可以指定路径、绝对路径等,默认在当前路径下
# -3, BaseException 此异常是python所有异常的基类,其他的异常均继承自它,此处是不明白具体的抛错种类,直接使用了基类
# -4, 数据库连接后记得关闭