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


猜你喜欢
- 目录一、代码分析二、完整代码写在最后想必写毕设的时候,大家都会遇到一个问题,那就是得在明评版的论文里面插入一个独创性声明。就因为这个事情,我
- 1、linux系统一般自带perl可运行程序在:/usr/bin/perl2、perl测试程序#!/usr/bin/perl -wuse w
- 常见的SQL问题:◆选择重复,消除重复和选择出序列有例表:empemp_no name age001 Tom 17002 Sun 14003
- 简介canvas 是HTML5 提供的一种新标签,它可以支持 JavaScript 在上面绘画,控制每一个像素,它经常被用来制作小游戏,接下
- 概念关键字:array,数据的组合(多个)存储到一个指定的容器中,用变量指向该容器,然后可以通过变量一次性得到该容器中的所有数据.数组定义语
- 在看视频教程的时候提到了[{'a' : 97}, {'b' : 98}, {'c' : 99
- 先准备好安装软件。从官网下载最新的pycharm版本:https://www.jetbrains.com/pycharm/download/
- 前言在做图像处理的时候,有时候需要得到整个数据集的均值方差数值,以下代码可以解决你的烦恼:(做这个之前一定保证所有的图片都是统一尺寸,不然算
- 最近一直跟着廖大在学Python,关于分布式进程的小例子挺有趣的,这里做个记录。分布式进程Python的multiprocessing模块不
- 使用的这么长时间的mysql,有一天我突然需要使用mysql 的配置文件my.ini时发现没有这个文件并且这个文件不是被隐藏了。查看自己的m
- 最近写了两个管理后台的前端页面,其中有一个管理后台,左侧菜单导航和右侧内容页是两个iframe,需求是,点击上面的主导航时,左侧iframe
- pygal的安装大家可以参阅:pip和pygal的安装实例教程线图:import pygalline_chart = pygal.Line(
- 看到php的错误日志里有些这样的提示: [27-Aug-2011 22:26:12] PHP Warning: Cannot use a s
- bs4的安装要使用BeautifulSoup4需要先安装lxml,再安 * s4pip install lxmlpip install bs4
- 在raft中,选取成功后集群就可以正常工作,一次正常的客户端提案过程如下:客户端连接到leader,发起提案leader收到提案后将提案,包
- 写在前面嗯,学习GO,所以有了这篇文章博文内容为《GO语言实战》读书笔记之一主要涉及映射相关知识你要爱就要像一个痴情的恋人那样去爱,像一个忘
- 使用SQL Server事件探查器工具,你可用一个捕获到的跟踪来收集有关服务器的重要信息。与索引优化向导(Index Tuning Wiza
- **问题描述:**有如下程序输出日志,计算程序运行时间,显示花费623分钟?start time:2019-03-15 19:45:31.2
- tensorlfow网络模型可视化。baidu了一些方法,现在介绍下我的流程和遇到的问题:配置window7tensorlfow1.5ana
- 前言:『入门MySQL』系列文章已经完结,今后我的文章还是会以MySQL为主,主要记录下近期工作及学习遇到的场景或者自己的感悟想法,可能后续