Python 操作SQLite数据库的示例
作者:lyshark 发布时间:2024-01-28 00:23:59
标签:Python,操作,SQLite,数据库
SQLite,是一款轻型的数据库,是遵守ACID的关系型数据库管理系统,它包含在一个相对小的C库中。在很多嵌入式产品中使用了它,它占用资源非常的低,python 中默认继承了操作此款数据库的引擎 sqlite3 说是引擎不如说就是数据库的封装版,开发自用小程序的使用使用它真的大赞
简单操作SQLite数据库:创建 sqlite数据库是一个轻量级的数据库服务器,该模块默认集成在python中,开发小应用很不错.
import sqlite3
# 数据表的创建
conn = sqlite3.connect("data.db")
cursor = conn.cursor()
create = "create table persion(" \
"id int auto_increment primary key," \
"name char(20) not null," \
"age int not null," \
"msg text default null" \
")"
cursor.execute(create) # 执行创建表操作
简单操作SQLite数据库:简单的插入语句的使用
insert = "insert into persion(id,name,age,msg) values(1,'lyshark',1,'hello lyshark');"
cursor.execute(insert)
insert = "insert into persion(id,name,age,msg) values(2,'guest',2,'hello guest');"
cursor.execute(insert)
insert = "insert into persion(id,name,age,msg) values(3,'admin',3,'hello admin');"
cursor.execute(insert)
insert = "insert into persion(id,name,age,msg) values(4,'wang',4,'hello wang');"
cursor.execute(insert)
insert = "insert into persion(id,name,age,msg) values(5,'sqlite',5,'hello sql');"
cursor.execute(insert)
data = [(6, '王舞',8, 'python'), (7, '曲奇',8,'python'), (9, 'C语言',9,'python')]
insert = "insert into persion(id,name,age,msg) values(?,?,?,?);"
cursor.executemany(insert,data)
简单的查询语句的使用
select = "select * from persion;"
cursor.execute(select)
#print(cursor.fetchall()) # 取出所有的数据
select = "select * from persion where name='lyshark';"
cursor.execute(select)
print(cursor.fetchall()) # 取出所有的数据
select = "select * from persion where id >=1 and id <=2;"
list = cursor.execute(select)
for i in list.fetchall():
print("字段1:", i[0])
print("字段2:", i[1])
简单的更新数据与删除
update = "update persion set name='苍老师' where id=1;"
cursor.execute(update)
update = "update persion set name='苍老师' where id>=1 and id<=3;"
cursor.execute(update)
delete = "delete from persion where id=3;"
cursor.execute(delete)
select = "select * from persion;"
cursor.execute(select)
print(cursor.fetchall()) # 取出所有的数据
conn.commit() # 事务提交,每执行一次数据库更改的操作,就执行提交
cursor.close()
conn.close()
SQLite小试牛刀 实现用户名密码验证,当用户输入错误密码后,自动锁定该用户1分钟.
import sqlite3
import re,time
conn = sqlite3.connect("data.db")
cursor = conn.cursor()
"""create = "create table login(" \
"username text not null," \
"password text not null," \
"time int default 0" \
")"
cursor.execute(create)
cursor.execute("insert into login(username,password) values('admin','123123');")
cursor.execute("insert into login(username,password) values('guest','123123');")
cursor.execute("insert into login(username,password) values('lyshark','1231');")
conn.commit()"""
while True:
username = input("username:") # 这个地方应该严谨验证,尽量不要让用户拼接SQL语句
password = input("passwor:") # 此处为了方便不做任何验证(注意:永远不要相信用户的输入)
sql = "select * from login where username='{}'".format(username)
ret = cursor.execute(sql).fetchall()
if len(ret) != 0:
now_time = int(time.time())
if ret[0][3] <= now_time:
print("当前用户{}没有被限制,允许登录...".format(username))
if ret[0][0] == username:
if ret[0][1] == password:
print("用户 {} 登录成功...".format(username))
else:
print("用户 {} 密码输入有误..".format(username))
times = int(time.time()) + 60
cursor.execute("update login set time={} where username='{}'".format(times,username))
conn.commit()
else:
print("用户名正确,但是密码错误了...")
else:
print("账户 {} 还在限制登陆阶段,请等待1分钟...".format(username))
else:
print("用户名输入错误")
SQLite检索时间记录 通过编写的TimeIndex函数检索一个指定范围时间戳中的数据.
import os,time,datetime
import sqlite3
"""
conn = sqlite3.connect("data.db")
cursor = conn.cursor()
create = "create table lyshark(" \
"time int primary key," \
"cpu int not null" \
")"
cursor.execute(create)
# 批量生成一堆数据,用于后期的测试.
for i in range(1,500):
times = int(time.time())
insert = "insert into lyshark(time,cpu) values({},{})".format(times,i)
cursor.execute(insert)
conn.commit()
time.sleep(1)"""
# db = data.db 传入数据库名称
# table = 指定表lyshark名称
# start = 2019-12-12 14:28:00
# ends = 2019-12-12 14:29:20
def TimeIndex(db,table,start,ends):
start_time = int(time.mktime(time.strptime(start,"%Y-%m-%d %H:%M:%S")))
end_time = int(time.mktime(time.strptime(ends,"%Y-%m-%d %H:%M:%S")))
conn = sqlite3.connect(db)
cursor = conn.cursor()
select = "select * from {} where time >= {} and time <= {}".format(table,start_time,end_time)
return cursor.execute(select).fetchall()
if __name__ == "__main__":
temp = TimeIndex("data.db","lyshark","2019-12-12 14:28:00","2019-12-12 14:29:00")
SQLite提取数据并绘图 通过使用matplotlib这个库函数,并提取出指定时间的数据记录,然后直接绘制曲线图.
import os,time,datetime
import sqlite3
import numpy as np
from matplotlib import pyplot as plt
def TimeIndex(db,table,start,ends):
start_time = int(time.mktime(time.strptime(start,"%Y-%m-%d %H:%M:%S")))
end_time = int(time.mktime(time.strptime(ends,"%Y-%m-%d %H:%M:%S")))
conn = sqlite3.connect(db)
cursor = conn.cursor()
select = "select * from {} where time >= {} and time <= {}".format(table,start_time,end_time)
return cursor.execute(select).fetchall()
def Display():
temp = TimeIndex("data.db","lyshark","2019-12-12 14:28:00","2019-12-12 14:29:00")
list = []
for i in range(0,len(temp)):
list.append(temp[i][1])
plt.title("CPU Count")
plt.plot(list, list)
plt.show()
if __name__ == "__main__":
Display()
文章作者:lyshark
文章出处:https://www.cnblogs.com/lyshark
来源:https://www.cnblogs.com/LyShark/p/12172674.html
0
投稿
猜你喜欢
- 不知道在坛子里有多少朋友使用触发器,如果你已经对触发器很了解了,那么请跳过此文,如果你还没有使用过触发器的话,那就让我们来认识一下吧。相关阅
- 本段代码是先将需要转换经纬度的地址爬取在 ‘地址.csv' 文件里,文件截图示例:代码展示# coding=utf-8# SPL#
- Python os 模块os是“operating system”的缩写,os模块提供各种 Pyth
- 前言在Python中已经内置了一个smtp邮件发送模块,Django在此基础上进行了简单地封装,让我们在Django环境中可以更方便更灵活的
- 前言十三届全国人大三次会议作了政府工作报告。这份政府工作报告仅有10500字左右,据悉是改革开放40年以来最短的一次。受到疫情影响,今年的两
- 最近在用python写接口的测试程序,期间用到解析字典获取某个key的value,由于多个接口返回的字典格式不是固定的并存在多层嵌套的情况。
- “博客就像一本书”这话其实几个月前深圳FB时就有扯到,这也不是什么新概念,也许本身就应该是这样。打个比方,当你拿到一本未看过的书时,理论上你
- 定义通用视图修改 book/models.py 代码中的 AuthorInfo 类,如果一致则不必修改class AuthorInfo(mo
- Python 链接抖音python下载抖音内容的帖子网上有一些,但都比较麻烦,需要通过adb连接安卓手机后,模拟操作。我这么懒,这种事儿玩不
- 当我们使用访问一个没有声明的变量时,JS会报错;而当我们给一个没有声明的变量赋值时,JS不会报错误,相反它会认为我们是要隐式申明一个全局变量
- 自定义比较排序/运算符Python3和Python2相比有挺多变化。在Python2中可以直接写一个cmp函数作为参数传入sort来自定义排
- 要使用摄像头,需要使用cv2.VideoCapture(0)创建VideoCapture对象,参数0指的是摄像头的编号,如果你电脑上有两个摄
- 本文实例讲述了Python 私有化操作。分享给大家供大家参考,具体如下:私有化xx: 公有变量_x: 单前置下划线,私有化属性或方法,fro
- 一、继承的格式类的继承格式如下,括号中的为父类名。class 类名(父类名): 代码二、单继承下面我们让Man继承自Master类,并调用继
- 如下所示:import numpy as npnp.set_printoptions(threshold='nan')来源:
- 大家先看一下Python os模块中的部分函数python 路径相关的函数 os.listdir(dirname):列出dirname下的目
- 楔子随着自媒体时代,现在对视频的处理变得越来越常见。我们可以使用Adobe的一些专业工具,但是效率不高;如果只是对视频进行一些简单的处理的话
- 1. 目的每天上班,工作需要,电脑上需要每天开机启动一些软件,下班时候,需要关掉一些软件。一个一个打开和关闭貌似是很繁琐的,于是乎,这个脚本
- 最近在学web自动化,记录一下学习过程。此处我选用python3.6+selenium3.0,均用最新版本,以适应未来需求。环境:windo
- 为了防止网络上日益猖獗的垃圾广告和灌水评论,大多数网站在信息发布的时候要求输入验证码。图片、文字、字母甚至还有计算题。验证码图片里的信息东颠