python—数据库SQLite3操作

目录

SQLite3数据库

Python语言操作SQLite3数据库的基本流程

创建连接数据库

插入数据

查询数据库

SQLite3可视化工具

SQLite3数据库

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

Python语言操作SQLite3数据库的基本流程

(1)导入相关库或模块(SQLite3)
(2)使用connect()连接数据库并获取数据库连接对象。它提供了以下方法:
.cursor()方法来创建一个游标对象
.commit()方法来处理事务提交
.rollback()方法来处理事务回滚
.close()方法来关闭一个数据库连接
(3)使用con.cursor()获取游标对象
(4)使用游标对象的方法(execute()、executemany()、 fetchall()等)来操作数据库,实现插入、修改和删除操作,并查询获取显示相关的记录。在Python程序中,连接函数sqlite3 connect()有如下两个常用参数:
database:表示要访问的数据库名
timeout:表示访问数据的超时设定
(5)使用close()关闭游标对象和数据库连接。数据库操作完成之后,必须及时调用其close()方法关闭数据库连接,这样做的目的是减轻数据库服务器的压力。

创建连接数据库

有则连接,无则创建并连接

import sqlite3

con = sqlite3.connect('../demosql/sql.db')  # 硬盘上创建并连接数据库对象(有则连接,无则创建并连接)
cur = con.cursor()  # 创建游标对象
sql = '''
create table newtable(
name varchar(8),
age int(3))
'''

try:
    cur.execute(sql)
    print('创建表成功')
except Exception as e:
    print(e)
    print('创建表执行失败')
finally:
    cur.close()  # 关闭游标
    con.close()  # 关闭连接

插入数据

一次插入一条数据

import sqlite3

con = sqlite3.connect('../demosql/sql.db')  # 硬盘上创建并连接数据库对象(有则连接,无则创建并连接)
cur = con.cursor()  # 创建游标对象
sql = "insert into newtable(name,age) values('刘备',56)"
sql = "insert into newtable(name,age) values(?,?)"

try:
    cur.execute(sql,('关羽',68))   # 执行一条数据的插入
    con.commit()  # 提交事务,不提交只会执行语句,但没有数据插入
    print('插入一条数据成功')
except Exception as e:
    print(e)
    con.rollback()   # 插入失败时回滚
    print('插入数据失败')
finally:
    cur.close()  # 关闭游标
    con.close()  # 关闭连接

一次插入多条数据

import sqlite3

con = sqlite3.connect('../demosql/sql.db')  # 硬盘上创建并连接数据库对象(有则连接,无则创建并连接)
cur = con.cursor()  # 创建游标对象
sql = "insert into newtable(name,age) values(?,?)"  # 使用?做占位符
data = [('孙权', 73), ('周瑜', 36), ('曹植', 42)]

try:
    # 执行多条数据的插入,多组数据在一个列表中,列表中的每组数据为元组形式,如果每组中只有一个数据时,需要加 , 表示数据格式为元组
    cur.executemany(sql, data)
    con.commit()  # 提交事务,不提交只会执行语句,但没有数据插入
    print('插入多条数据成功')
except Exception as e:
    print(e)
    con.rollback()  # 插入失败时回滚
    print('插入数据失败')
finally:
    cur.close()  # 关闭游标
    con.close()  # 关闭连接

SQLite3 的sql语句占位符使用?,mysql数据库使用%s

查询数据库

用法同mysql:python—mysql数据库_北冥有鱼的博客-CSDN博客_py-mysql

import sqlite3

con = sqlite3.connect('../demosql/sql.db')  # 硬盘上创建并连接数据库对象(有则连接,无则创建并连接)
cur = con.cursor()  # 创建游标对象
sql = "select * from newtable"

try:
    cur.execute(sql)
    print(cur.fetchone())  # 返回一个元组
    # print(cur.fetchmany(3))  # 返回一个列表
    print(cur.fetchall())  # 返回一个列表
except Exception as e:
    print(e)
    con.rollback()
    print('插入数据失败')
finally:
    cur.close()  # 关闭游标
    con.close()  # 关闭连接

SQLite3可视化工具

python—数据库SQLite3操作

Original: https://blog.csdn.net/JBY2020/article/details/122315022
Author: 觅远
Title: python—数据库SQLite3操作

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/815796/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球