python使用sqlite3数据库以及组合使用try catch

话不多说,直接贴出使用代码

#!/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, 数据库连接后记得关闭
  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值