Python 操作SQLite数据库详情
作者:lyshark 发布时间:2024-01-18 04:45:55
标签:Python,操作,SQLite,数据库
前言:
SQLite
属于轻型数据库,遵守ACID
的关系型数据库管理系统,它包含在一个相对小的C库中。在很多嵌入式产品中使用了它,它占用资源非常的低,python
中默认继承了操作此款数据库的引擎 sqlite3
说是引擎不如说就是数据库的封装版,开发自用小程序的使用使用它真的大赞
一、简单操作SQLite数据库
简单操作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) # 执行创建表操作
1、简单的插入语句的使用
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)
2、简单的查询语句的使用
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()
三、实现用户名密码验证
当用户输入错误密码后,自动锁定该用户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")
print(temp)
五、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()
来源:https://www.cnblogs.com/LyShark/p/12172674.html


猜你喜欢
- Python编写从ZabbixAPI获取信息此脚本用Python3.6执行是OK的。# -*- coding: utf-8 -*-impor
- 前言Tkinter(即 tk interface) 是 Python 标准 GUI 库,简称 “Tk&rdquo
- 1、搭载QT环境按win+R输入 pip install pyqt5 下载QT5 当然也可以去Qt的官网的下载 ,使用命令行更快捷方便 所以
- vue-cli-service build 环境设置使用vue-cli3打包项目,通过配置不同的指令给项目设置不一样的配置。npm run
- 当数组/矩阵过大则只会显示其中一部分,中间则会自动用省略号代替:直接在import numpy 加上下面一句代码即可解决:import nu
- 本文实例讲述了常规方法实现python数组的全排列操作。分享给大家供大家参考。具体分析如下:全排列解释:从n个不同元素中任取m(m≤n)个元
- vue中引入html静态页面功能:系统中需增加帮助中心页面,由于页面较长,需要实现锚点定位跳转。1、开始用的路由方式,首先在router文件
- 作者的blog: blog.never-online.net"Never Modules"-NCC(never
- 重装电脑,在windows和虚拟机里面的Ubuntu里都安装了Pycharm专业版,安装的时候我都选择了vim插件,装好之后打开发现ctrl
- 如下所示:s=subprocess.Popen("ping baidu.com -t",bufsize=0,stdout
- Matplotlib介绍Matplotlib 是一款用于数据可视化的 Python 软件包,支持跨平台运行,它能够根据 NumPy 
- 标记路径演示效果:实例代码import matplotlib.pyplot as pltimport matplotlib.path as
- splinter介绍 Splinter是一个使用Python测试Web应用程序的开源工具,可以自动化浏览器操作,例如访问URL和与它们的项
- # -*-coding:utf-8-*-import sys, os'''将当前进程fork为一个守护进程注意:如果
- 简单单例模式单例模式是创建类型的模式,它是为了保证执行期间内只有一个实例。使用 Golang 指针可以很容易的实现单例模式,通过指针保持相同
- 1、简要说明结巴分词支持三种分词模式,支持繁体字,支持自定义词典2、三种分词模式全模式:把句子中所有的可以成词的词语都扫描出来, 速度非常快
- selenium 介绍selenium 是一个 web 的自动化测试工具,不少学习功能自动化的同学开始首选 selenium ,因为它相比
- 背景:之前写的接口测试一直没有支持无限嵌套对比key,上次testerhome逛论坛,有人分享了他的框架,看了一下,有些地方不合适我这边自己
- 今天主要记录一下pandas去重复行以及如何分类汇总。以下面的数据帧作为一个例子: import pandas as pddata
- <%@ Page Language="C#" %><!DOCTYPE html PUBLIC &quo