Python 操作SQLite3数据库的实现示例

Written by

in

文章目录
  • 使用 sqlite3 模块的 connect 方法来创建/打开数据库,需要指定数据库路径,不存在则创建一个新的数据库。 con=sqlite3.connect(‘/home/blctrl/sqlite-db/first.db’) 下面实例代码演示使用 SQLite3 创建数据库的过程。 # 导入 sqlite3 模块 import sqlite3 # 1.硬盘上创建连接 con = sqlite3.connect(‘/home/blctrl/sqlite-db/example.db’) # 获取 cursor 对象 cur = con.cursor() # 执行 sql 创建表 sql = ”’ CREATE TABLE t_person( pno INTEGER PRIMARY KEY AUTOINCREMENT , pname varchar(30) NOT NULL, age INTEGER) ”’ try: cur.execute(sql) except Exception as e: print(e) print(‘创建表失败’) finally: # 关闭游标 cur.close() # 关闭连接 con.close() 在IPython下测试: In [1]: import sqlite3 In [2]: con = sqlite3.connect(‘/home/blctrl/sqlite-db/example.db’) In [3]: cur = con.cursor() In [4]: sql = ”’ …: CREATE TABLE t_person( …: pno INTEGER PRIMARY KEY AUTOINCREMENT , …: pname varchar(30) NOT NULL, …: age INTEGER) …: ”’ …: In [5]: try: …: cur.execute(sql) …: print(‘create Table successfully!’) …: except Exception as e: …: print(e) …: print(“Failed to create table!”) …: finally: …: cur.close() …: con.close() …: create Table successfully!
  • 调用游标对象的 execute 执行插入的 sql,使用 executemany() 执行多条 sql 语句,使用 executemany()比循环使用execute()执行多条sql语句效率高. 示例: 使用SQLite3插入一条数据 # 导入 sqllite3 模块 import sqlite3 # 硬盘上创建连接 con = sqlite3.connect(‘/home/blctrl/sqlite-db/example.db’) # 获取 cursor 对象 cur = con.cursor() # 构造sql插入语句 sql = ‘insert into t_person(pname,age) values(?,?)’ try: cur.execute(sql,(‘XRR’,23)) # 插入多条 cur.executemany(sql, [(‘XFS’, 25),(‘XPS’, 21), (‘XRD’, 30)]) # 提交事务 con.commit() print(‘插入成功’) except Exception as e: print(e) print(‘插入失败’) con.rollback() finally: # 关闭游标 cur.close() # 关闭连接 con.close() 在IPython中进行单条数据插入的测试: In [12]: con = sqlite3.connect(‘/home/blctrl/sqlite-db/example.db’) In [13]: cur = con.cursor() In [14]: sql = ‘insert into t_person(pname,age) values(?,?)’ In [15]: try: …: cur.execute(sql, (‘XRR’,28)) …: con.commit() …: print(“Insert successfully”) …: except Exception as e: …: print(e) …: print(“Insert failed”) …: con.rollback() …: finally: …: cur.close() …: con.close() …: Insert successfully 在IPython中进行多条数据插入的测试: In [16]: con = sqlite3.connect(‘/home/blctrl/sqlite-db/example.db’) In [17]: cur = con.cursor() In [18]: sql = ‘insert into t_person(pname,age) values(?,?)’ In [19]: try: …: cur.executemany(sql, [(‘XFS’, 25),(‘XPS’, 21), (‘XRD’, 30)]) …: con.commit() …: print(“Many insert successfully”) …: except Exception as e: …: print(e) …: print(“Many insert failed”) …: con.rollback() …: finally: …: cur.close() …: con.close() …: Many insert successfully
  • 查询数据,游标对象提供了 fetchall() 和 fetchone() 方法。fetchall() 方法获取所有数据,返回一个列表。fetchone() 方法获取其中一个结果,返回一个元组。 【示例】fetchall() 查询所有数据 # 导入 sqllite3 模块 import sqlite3 # 硬盘上创建连接 con = sqlite3.connect(‘/home/blctrl/sqlite-db/example.db’) # 获取 cursor 对象 cur = con.cursor() # 创建查询SQL语句 sql = ‘SELECT * FROM t_person’ try: cur.execute(sql) # 获取所有数据 person_all = cur.fetchall() # person = cur.fetchone() 获取一条数据 # print(person_all) # 遍历 for p in person_all: print(p) except Exception as e: print(e) print(‘查询失败’) finally: # 关闭游标 cur.close() # 关闭连接 con.close() 使用IPython测试: In [1]: import sqlite3 In [2]: con = sqlite3.connect(‘/home/blctrl/sqlite-db/example.db’) In [3]: cur = con.cursor() In [4]: sql = ‘SELECT * FROM t_person’; In [5]: try: …: cur.execute(sql) …: person_all = cur.fetchall() …: for p in person_all: …: print(p) …: except Exception as e: …: print(e) …: print(‘acquire failed’) …: finally: …: cur.close() …: con.close() …: (1, ‘XRR’, 28) (2, ‘XFS’, 25) (3, ‘XPS’, 21) (4, ‘XRD’, 30)
  • # 导入 sqllite3 模块 import sqlite3 # 硬盘上创建连接 con = sqlite3.connect(‘/home/blctrl/sqlite-db/example.db’) # 获取 cursor 对象 cur = con.cursor() # 构造更新数据的sql语句 update_sql = ‘update t_person set pname=? where pno=?’ try: cur.execute(update_sql, (‘ABC’, 1)) # 提交事务 con.commit() print(‘修改成功’) except Exception as e: print(e) print(‘修改失败’) con.rollback() finally: cur.close() con.close() IPython中测试修改: In [6]: con = sqlite3.connect(‘/home/blctrl/sqlite-db/example.db’) In [7]: cur = con.cursor() In [8]: update_sql = ‘UPDATE t_person SET pname=? WHERE pno=?’ In [9]: try: …: cur.execute(update_sql, (‘ABC’, 1)) …: con.commit() …: print(‘Modify Successfully’) …: except Exception as e: …: print(e) …: con.rollback() …: print(‘Modify failed’) …: finally: …: cur.close() …: con.close() …: Modify Successfully
  • # 导入 sqllite3 模块 import sqlite3 # 硬盘上创建连接 con = sqlite3.connect(‘/home/blctrl/sqlite-db/example.db’) # 获取 cursor 对象 cur = con.cursor() # 构造更新数据的sql语句 delete_sql = ‘DELETE FROM t_person where pno=?’ try: cur.execute(delete_sql, (1,)) # 提交事务 con.commit() print(‘删除成功’) except Exception as e: print(e) print(‘删除失败’) con.rollback() finally: cur.close() con.close() IPython中测试删除: In [14]: con = sqlite3.connect(‘/home/blctrl/sqlite-db/example.db’) In [15]: cur = con.cursor() In [16]: delete_sql = ‘DELETE FROM t_person WHERE pno=?’ In [17]: try: …: cur.execute(delete_sql, (1,)) …: con.commit() …: print(‘DELETE Successfully’) …: except Exception as e: …: print(e) …: print(‘DELETE failed’) …: con.rollback() …: finally: …: cur.close() …: con.close() …: DELETE Successfully 到此这篇关于Python 操作SQLite3数据库的文章就介绍到这了,更多相关Python 操作SQLite3内容请搜索风君子博客以前的文章或继续浏览下面的相关文章希望大家以后多多支持风君子博客! 您可能感兴趣的文章: python连接sqlite3简单用法完整例子 通过python封装SQLite3的示例代码 Python的sqlite3模块中常用函数 Python数据库sqlite3图文实例详解 Python标准库之数据库 sqlite3 python3 sqlite3限制条件查询的操作 Python使用sqlite3模块内置数据库
  • 目录
    • 使用 SQLite3 创建表
    • 使用 SQLite3 插入数据
    • 使用 SQLite3 查询数据
    • 使用 SQLite3 修改数据
    • 使用 SQLite3 删除数据

    从 Python3.x 版本开始,在标准库中已经内置了 SQLite3 模块,它可以支持 SQLite3 数据库的访问和相关的数据库操作。在需要操作 SQLite3 数据库数据时,只须在程序中导入 SQLite3 模块即可。Python 语言操作 SQLite3 数据库的基本流程如下所示。

    (1) 导入相关库或模块(SQLite3)。

    (2) 使用 connect() 连接数据库并获取数据库连接对象。它提供了以下方法:

    1. .cursor() 方法来创建一个游标对象
    2. .commit() 方法来处理事务提交
    3. .rollback() 方法来处理事务回滚
    4. .close() 方法来关闭一个数据库连接

    (3) 使用 con.cursor() 获取游标对象。

    (4) 使用游标对象的方法(execute()、executemany()、fetchall()等)来操作数据库,实现插入、修改和删除操作,并查询获取显示相关的记录。在 Python 程序中,连接函数 sqlite3.connect() 有如下两个常用参数。

    1. database: 表示要访问的数据库名。
    2. timeout: 表示访问数据的超时设定。

    (5) 使用 close() 关闭游标对象和数据库连接。数据库操作完成之后,必须及时调用其 close() 方法关闭数据库连接,这样做的目的是减轻数据库服务器的压力。

    使用 sqlite3 模块的 connect 方法来创建/打开数据库,需要指定数据库路径,不存在则创建一个新的数据库。

    con=sqlite3.connect('/home/blctrl/sqlite-db/first.db')

    下面实例代码演示使用 SQLite3 创建数据库的过程。

    # 导入 sqlite3 模块
    import sqlite3
    
    # 1.硬盘上创建连接
    con = sqlite3.connect('/home/blctrl/sqlite-db/example.db')
    
    # 获取 cursor 对象
    cur = con.cursor()
    
    # 执行 sql 创建表
    sql = '''
        CREATE TABLE t_person(
            pno INTEGER PRIMARY KEY AUTOINCREMENT ,
            pname varchar(30) NOT NULL,
            age INTEGER)
    '''
    
    try:
        cur.execute(sql)
    
    except Exception as e:
        print(e)
        print('创建表失败')
    
    finally:
        # 关闭游标
        cur.close()
        # 关闭连接
        con.close()

    在IPython下测试:

    In [1]: import sqlite3
    
    In [2]: con = sqlite3.connect('/home/blctrl/sqlite-db/example.db')
    
    In [3]: cur = con.cursor()
    
    In [4]: sql = '''
       ...:     CREATE TABLE t_person(
       ...:         pno INTEGER PRIMARY KEY AUTOINCREMENT ,
       ...:         pname varchar(30) NOT NULL,
       ...:         age INTEGER)
       ...: '''
       ...:
    
    In [5]: try:
       ...:     cur.execute(sql)
       ...:     print('create Table successfully!')
       ...: except Exception as e:
       ...:     print(e)
       ...:     print("Failed to create table!")
       ...: finally:
       ...:     cur.close()
       ...:     con.close()
       ...:
    create Table successfully!

    调用游标对象的 execute 执行插入的 sql,使用 executemany() 执行多条 sql 语句,使用 executemany()比循环使用execute()执行多条sql语句效率高.

    示例: 使用SQLite3插入一条数据

    # 导入 sqllite3 模块
    import sqlite3
    
    # 硬盘上创建连接
    con = sqlite3.connect('/home/blctrl/sqlite-db/example.db')
    
    # 获取 cursor 对象
    cur = con.cursor()
    # 构造sql插入语句
    sql = 'insert into t_person(pname,age) values(?,?)'
    try:
        cur.execute(sql,('XRR',23))
        # 插入多条
        cur.executemany(sql, [('XFS', 25),('XPS', 21), ('XRD', 30)])
    # 提交事务
        con.commit()
        print('插入成功')
    except Exception as e:
        print(e)
        print('插入失败')
        con.rollback()
    finally:
        # 关闭游标
        cur.close()
        # 关闭连接
        con.close()
    
    

    在IPython中进行单条数据插入的测试:

    In [12]: con = sqlite3.connect('/home/blctrl/sqlite-db/example.db')
    
    In [13]: cur = con.cursor()
    
    In [14]: sql = 'insert into t_person(pname,age) values(?,?)'
    
    In [15]: try:
        ...:     cur.execute(sql, ('XRR',28))
        ...:     con.commit()
        ...:     print("Insert successfully")
        ...: except Exception as e:
        ...:     print(e)
        ...:     print("Insert failed")
        ...:     con.rollback()
        ...: finally:
        ...:     cur.close()
        ...:     con.close()
        ...:
    Insert successfully

    在IPython中进行多条数据插入的测试:

    In [16]: con = sqlite3.connect('/home/blctrl/sqlite-db/example.db')
    
    In [17]: cur = con.cursor()
    
    In [18]: sql = 'insert into t_person(pname,age) values(?,?)'
    
    In [19]: try:
        ...:     cur.executemany(sql, [('XFS', 25),('XPS', 21), ('XRD', 30)])
        ...:     con.commit()
        ...:     print("Many insert successfully")
        ...: except Exception as e:
        ...:     print(e)
        ...:     print("Many insert failed")
        ...:     con.rollback()
        ...: finally:
        ...:     cur.close()
        ...:     con.close()
        ...:
    Many insert successfully

    查询数据,游标对象提供了 fetchall() 和 fetchone() 方法。fetchall() 方法获取所有数据,返回一个列表。fetchone() 方法获取其中一个结果,返回一个元组。

    【示例】fetchall() 查询所有数据

    # 导入 sqllite3 模块
    import sqlite3
    
    # 硬盘上创建连接
    con = sqlite3.connect('/home/blctrl/sqlite-db/example.db')
    
    # 获取 cursor 对象
    cur = con.cursor()
    
    # 创建查询SQL语句
    sql = 'SELECT * FROM t_person'
    try:
        cur.execute(sql)
        # 获取所有数据
        person_all = cur.fetchall()
        # person = cur.fetchone() 获取一条数据
        # print(person_all)
        # 遍历
        for p in person_all:
            print(p)
    except Exception as e:
        print(e)
        print('查询失败')
    finally:
        # 关闭游标
        cur.close()
        # 关闭连接
        con.close()

    使用IPython测试:

    In [1]: import sqlite3
    
    In [2]: con = sqlite3.connect('/home/blctrl/sqlite-db/example.db')
    
    In [3]: cur = con.cursor()
    
    In [4]: sql = 'SELECT * FROM t_person';
    
    In [5]: try:
       ...:     cur.execute(sql)
       ...:     person_all = cur.fetchall()
       ...:     for p in person_all:
       ...:         print(p)
       ...: except Exception as e:
       ...:     print(e)
       ...:     print('acquire failed')
       ...: finally:
       ...:     cur.close()
       ...:     con.close()
       ...:
    (1, 'XRR', 28)
    (2, 'XFS', 25)
    (3, 'XPS', 21)
    (4, 'XRD', 30)

    # 导入 sqllite3 模块
    import sqlite3
    
    # 硬盘上创建连接
    con = sqlite3.connect('/home/blctrl/sqlite-db/example.db')
    
    # 获取 cursor 对象
    cur = con.cursor()
    # 构造更新数据的sql语句
    update_sql = 'update t_person set pname=? where pno=?'
    try:
        cur.execute(update_sql, ('ABC', 1))
    
        # 提交事务
        con.commit()
        print('修改成功')
    
    except Exception as e:
        print(e)
        print('修改失败')
        con.rollback()
    
    finally:
        cur.close()
        con.close()

    IPython中测试修改:

    In [6]: con = sqlite3.connect('/home/blctrl/sqlite-db/example.db')
    
    In [7]: cur = con.cursor()
    
    In [8]: update_sql = 'UPDATE t_person SET pname=? WHERE pno=?'
    
    In [9]: try:
       ...:     cur.execute(update_sql, ('ABC', 1))
       ...:     con.commit()
       ...:     print('Modify Successfully')
       ...: except Exception as e:
       ...:     print(e)
       ...:     con.rollback()
       ...:     print('Modify failed')
       ...: finally:
       ...:     cur.close()
       ...:     con.close()
       ...:
    Modify Successfully

    # 导入 sqllite3 模块
    import sqlite3
    
    # 硬盘上创建连接
    con = sqlite3.connect('/home/blctrl/sqlite-db/example.db')
    
    # 获取 cursor 对象
    cur = con.cursor()
    # 构造更新数据的sql语句
    delete_sql = 'DELETE FROM t_person where pno=?'
    try:
        cur.execute(delete_sql, (1,))
    
        # 提交事务
        con.commit()
        print('删除成功')
    
    except Exception as e:
        print(e)
        print('删除失败')
        con.rollback()
    
    finally:
        cur.close()
        con.close()

    IPython中测试删除:

    In [14]:  con = sqlite3.connect('/home/blctrl/sqlite-db/example.db')
    
    In [15]:  cur = con.cursor()
    
    In [16]: delete_sql = 'DELETE FROM t_person WHERE pno=?'
    
    In [17]: try:
        ...:     cur.execute(delete_sql, (1,))
        ...:     con.commit()
        ...:     print('DELETE Successfully')
        ...: except Exception as e:
        ...:     print(e)
        ...:     print('DELETE failed')
        ...:     con.rollback()
        ...: finally:
        ...:     cur.close()
        ...:     con.close()
        ...:
    DELETE Successfully

    到此这篇关于Python 操作SQLite3数据库的文章就介绍到这了,更多相关Python 操作SQLite3内容请搜索风君子博客以前的文章或继续浏览下面的相关文章希望大家以后多多支持风君子博客!

    您可能感兴趣的文章:

    • python连接sqlite3简单用法完整例子
    • 通过python封装SQLite3的示例代码
    • Python的sqlite3模块中常用函数
    • Python数据库sqlite3图文实例详解
    • Python标准库之数据库 sqlite3
    • python3 sqlite3限制条件查询的操作
    • Python使用sqlite3模块内置数据库

    站内搜索