Python使用sqlite3模块内置数据库
作者:夏日的向日葵 时间:2024-01-26 21:51:39
1、python内置的sqlite3模块,创建数据库中的表,并向表中插入数据,从表中取出所有行,以及输出行的数量。
#!/usr/bin/env python3
#创建SQLite3内存数据库,并创建带有四个属性的sales表
#sqlite3模块,提供了一个轻量级的基于磁盘的数据库,不需要独立的服务器进程
import sqlite3
#使用‘:memory:'在内存中创建了一个数据库,创建了连接对象con来代表数据库
con = sqlite3.connect(':memory:')
#创建表名为sales的表,将这个字符串赋值给query
query = """CREATE TABLE sales
(customer VARCHAR(20),
product VARCHAR(40),
amount FLOAT,
date DATE);"""
#使用连接对象的execute()方法执行query中的SQL命令
con.execute(query)
#使用连接对象的commit()方法将修改提交(保存)到数据库
con.commit()
#向表中插入几行数据
data = [('Richard Lucas','Notepad',2.50,'2019-01-02'),
('Jenny Kim','Binder',4.15,'2019-01-05'),
('Svetlana Crow','Printer',155.75,'2019-02-03'),
('Stephen Randolph','Computer',679.40,'2019-02-20')]
#将插入语句赋给变量statement,?是占位符
statement = "INSERT INTO sales VALUES(?,?,?,?)"
#因为有四个占位符,这里就需要提供一个包含4个值的元组,executemany()方法为data中的每个数据元组执行
#statement中的SQL命令,这里执行了四次insert命令
con.executemany(statement,data)
#将修改保存到数据库
con.commit()
#查询sales表,并将命令结果赋值给一个光标对象cursor,光标对象有execute、executemany、fetchone、
#fetchmany和fetchall方法
cursor = con.execute("SELECT * FROM sales")
#返回结果集中的所有行
rows = cursor.fetchall()
print(rows)
print('………………')
#查询结果中行的数量
row_counter = 0
for row in rows:
print(row)
row_counter += 1
print('………………')
print('Number of rows: %d' % (row_counter))
Spyder右下角打印出来的结果:
[('Richard Lucas', 'Notepad', 2.5, '2019-01-02'), ('Jenny Kim', 'Binder', 4.15, '2019-01-05'), ('Svetlana Crow', 'Printer', 155.75, '2019-02-03'), ('Stephen Randolph', 'Computer', 679.4, '2019-02-20')]
………………
('Richard Lucas', 'Notepad', 2.5, '2019-01-02')
('Jenny Kim', 'Binder', 4.15, '2019-01-05')
('Svetlana Crow', 'Printer', 155.75, '2019-02-03')
('Stephen Randolph', 'Computer', 679.4, '2019-02-20')
………………
Number of rows: 4
2、python内置的sqlite3模块,向表中插入新纪录
名称为“CSV测试数据.csv”的数据源:
将本地“CSV测试数据.csv”的数据导入到本地数据库football_game.db中:
#!/usr/bin/env python3
#创建SQLite3内存数据库,并创建带有四个属性的sales表
#sqlite3模块,提供了一个轻量级的基于磁盘的数据库,不需要独立的服务器进程
import sqlite3
import csv
input_file = "F://python入门//数据1//CSV测试数据.csv"
#为一个简单的本地数据库football_game.db创建连接,football_game.db为数据库名称
con = sqlite3.connect('football_game.db')
#创建了一个光标
c = con.cursor()
#如果表名存在,则删除它
drop_table = """DROP TABLE IF EXISTS football_game;"""
c.execute(drop_table)
con.commit()
#创建表名为football_game的表,将这个字符串赋值给create_table
create_table = """CREATE TABLE IF NOT EXISTS football_game
(name VARCHAR(20),
sex VARCHAR(10),
age INT,
score INT,
device_number VARCHAR(20),
cost VARCHAR(20));"""
#使用连接对象的execute()方法执行create_table中的SQL命令
c.execute(create_table)
#使用连接对象的commit()方法将修改提交(保存)到数据库
con.commit()
#从CSV格式的输入文件中读取要加载到数据库中的数据,创建file_reader对象,用于存储CSV中的数据集
file_reader = csv.reader(open(input_file,'r'),delimiter=',')
#从输入文件中读入第一行
header = next(file_reader,None)
#将输入的所有数据进行循环,先是每行循环,再是每列循环
for row in file_reader:
data = []
for column_index in range(len(header)):
data.append(row[column_index])
print(data)
c.execute("INSERT INTO football_game VALUES(?,?,?,?,?,?)",data)
#将修改保存到数据库
con.commit()
print('………………')
#执行选择所有数据的SQL
output = c.execute("SELECT * FROM football_game")
#返回结果集中的所有行,返回的是一个大的列表
rows = output.fetchall()
print(rows)
print('………………')
for row in rows:
output = []
for column_index in range(len(row)):
output.append(str(row[column_index]))
print(output)
Spyder右下角打印出来的结果:
['李刚', '男', '32', '567', '18512349553', '$500.00 ']
['王红', '女', '54', '423', '18256785181', '$750.00 ']
['孙晓', '女', '25', '457', '13698762112', '$250.00 ']
['郭亮', '男', '65', '350', '18654320816', '$125.00 ']
['高英', '女', '15', '390', '18511113141', '$815.00 ']
………………
[('李刚', '男', 32, 567, '18512349553', '$500.00 '), ('王红', '女', 54, 423, '18256785181', '$750.00 '), ('孙晓', '女', 25, 457, '13698762112', '$250.00 '), ('郭亮', '男', 65, 350, '18654320816', '$125.00 '), ('高英', '女', 15, 390, '18511113141', '$815.00 ')]
………………
['李刚', '男', '32', '567', '18512349553', '$500.00 ']
['王红', '女', '54', '423', '18256785181', '$750.00 ']
['孙晓', '女', '25', '457', '13698762112', '$250.00 ']
['郭亮', '男', '65', '350', '18654320816', '$125.00 ']
['高英', '女', '15', '390', '18511113141', '$815.00 ']
3、python内置的sqlite3模块,更新数据表中的记录
名称为“CSV测试数据.csv”的数据源:
更新表中的记录:
#!/usr/bin/env python3
#创建SQLite3内存数据库,并创建带有四个属性的sales表
#sqlite3模块,提供了一个轻量级的基于磁盘的数据库,不需要独立的服务器进程
import sqlite3
import csv
input_file = "F://python入门//数据1//CSV测试数据.csv"
#使用‘:memory:'在内存中创建了一个数据库,创建了连接对象con来代表数据库
con = sqlite3.connect(':memory:')
#创建表名为sales的表,将这个字符串赋值给query
query = """CREATE TABLE IF NOT EXISTS sales
(customer VARCHAR(20),
product VARCHAR(40),
amount FLOAT,
date DATE);"""
#使用连接对象的execute()方法执行query中的SQL命令
con.execute(query)
#使用连接对象的commit()方法将修改提交(保存)到数据库
con.commit()
#向表中插入几行数据
data = [('Richard Lucas','Notepad',2.50,'2019-01-02'),
('Jenny Kim','Binder',4.15,'2019-01-05'),
('Svetlana Crow','Printer',155.75,'2019-02-03'),
('Stephen Randolph','Computer',679.40,'2019-02-20')]
#for tuple in data:
# print(tuple)
#将插入语句赋给变量statement,?是占位符
statement = "INSERT INTO sales VALUES(?,?,?,?)"
#因为有四个占位符,这里就需要提供一个包含4个值的元组,executemany()方法为data中的每个数据元组执行
#statement中的SQL命令,这里执行了四次insert命令
con.executemany(statement,data)
#将修改保存到数据库
con.commit()
#读取CSV文件并更新特定的行
file_reader = csv.reader(open(input_file,'r'),delimiter=',')
#从输入文件中读入第一行
header = next(file_reader,None)
#将输入的所有数据进行循环,先是每行循环,再是每列循环
for row in file_reader:
data = []
for column_index in range(len(header)):
data.append(row[column_index])
con.execute("UPDATE sales SET amount=?,date=? where customer=?;",data)
#将修改保存到数据库
con.commit()
#查询sales表,并将命令结果赋值给一个光标对象cursor,光标对象有execute、executemany、fetchone、
#fetchmany和fetchall方法
cursor = con.execute("SELECT * FROM sales")
#返回结果集中的所有行
rows = cursor.fetchall()
print(rows)
print('………………')
for row in rows:
output = []
for column_index in range(len(row)):
output.append(str(row[column_index]))
print(output)
Spyder右下角打印出来的结果:
[('Richard Lucas', 'Notepad', 4.25, '2019-11-05'), ('Jenny Kim', 'Binder', 6.75, '2019-12-05'), ('Svetlana Crow', 'Printer', 155.75, '2019-02-03'), ('Stephen Randolph', 'Computer', 679.4, '2019-02-20')]
………………
['Richard Lucas', 'Notepad', '4.25', '2019-11-05']
['Jenny Kim', 'Binder', '6.75', '2019-12-05']
['Svetlana Crow', 'Printer', '155.75', '2019-02-03']
['Stephen Randolph', 'Computer', '679.4', '2019-02-20']
来源:https://www.cnblogs.com/xiao02fang/p/12638549.html
标签:Python,sqlite,模块,数据库
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
高性能表现的网站(译)
2008-08-31 20:26:00
![](https://img.aspxhome.com/file/UploadPic/20088/31/2008831203229237s.gif)
使用Python第三方库发送电子邮件的示例代码
2021-07-24 11:17:36
![](https://img.aspxhome.com/file/2023/6/97486_0s.jpg)
聊一聊Vue.js过渡效果
2024-05-13 09:07:51
![](https://img.aspxhome.com/file/2023/1/126651_0s.png)
Python脚本导出为exe程序的方法
2022-08-22 21:33:05
![](https://img.aspxhome.com/file/2023/3/121453_0s.png)
关于搜索建议的两点小问题
2011-09-16 20:15:29
mysql与mssql的md5加密语句
2024-01-20 07:33:22
Go语言中节省内存技巧方法示例
2024-02-10 16:43:40
当视觉设计师遇上产品经理、开发工程师…[译]
2010-01-17 10:18:00
![](https://img.aspxhome.com/file/UploadPic/20101/17/gui_vs_pm_01-86s.jpg)
JS中判断null、undefined与NaN的方法
2024-04-19 09:54:27
Python+Tensorflow+CNN实现车牌识别的示例代码
2021-06-30 08:44:05
![](https://img.aspxhome.com/file/2023/0/101460_0s.jpg)
Python tkinter之ComboBox(下拉框)的使用简介
2021-11-10 02:40:29
![](https://img.aspxhome.com/file/2023/3/127813_0s.png)
Go语言中结构体方法副本传参与指针传参的区别介绍
2024-05-05 09:29:45
php 静态页面中显示动态内容
2023-11-18 22:09:22
三十分钟MySQL快速入门(图解)
2024-01-21 21:49:32
![](https://img.aspxhome.com/file/2023/5/80015_0s.png)
ASP FCKeditor在线编辑器使用方法
2023-01-12 23:15:04
详解Python3.1版本带来的核心变化
2021-02-14 01:31:00
树莓派升级python的具体步骤
2023-08-04 00:28:49
JavaScript数学对象Math操作数字的方法
2024-04-10 10:54:34
Windows下Python2与Python3两个版本共存的方法详解
2022-01-16 12:27:29
![](https://img.aspxhome.com/file/2023/8/111888_0s.jpg)
重命名批处理python脚本
2021-04-27 22:56:38