Python 操作SQLite数据库的示例


Posted in Python onOctober 16, 2020

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

以上就是Python 操作SQLite数据库的示例的详细内容,更多关于Python 操作SQLite数据库的资料请关注三水点靠木其它相关文章!

Python 相关文章推荐
python中bisect模块用法实例
Sep 25 Python
python持久性管理pickle模块详细介绍
Feb 18 Python
python将字符串以utf-8格式保存在txt文件中的方法
Oct 30 Python
利用python实现简易版的贪吃蛇游戏(面向python小白)
Dec 30 Python
Python supervisor强大的进程管理工具的使用
Apr 24 Python
Django实现发送邮件找回密码功能
Aug 12 Python
python循环嵌套的多种使用方法解析
Nov 29 Python
python小程序基于Jupyter实现天气查询的方法
Mar 27 Python
django 解决自定义序列化返回处理数据为null的问题
May 20 Python
使用keras和tensorflow保存为可部署的pb格式
May 25 Python
Python优秀开源项目Rich源码解析的流程分析
Jul 06 Python
python实现腾讯滑块验证码识别
Apr 27 Python
python Selenium 库的使用技巧
Oct 16 #Python
用Python进行websocket接口测试
Oct 16 #Python
python如何控制进程或者线程的个数
Oct 16 #Python
python利用 keyboard 库记录键盘事件
Oct 16 #Python
python实现快速文件格式批量转换的方法
Oct 16 #Python
Python通过getattr函数获取对象的属性值
Oct 16 #Python
pandas处理csv文件的方法步骤
Oct 16 #Python
You might like
深入HTTP响应状态码速查表的详解
2013/06/07 PHP
分割GBK中文遭遇乱码的解决方法
2013/08/09 PHP
PHP读取PPT文件的方法
2015/12/10 PHP
验证token、回复图文\文本、推送消息的实用微信类php代码
2016/06/28 PHP
PHP简单日历实现方法
2016/07/20 PHP
PHP基于cookie实现统计在线人数功能示例
2019/01/16 PHP
PHP接口类(interface)的定义、特点和应用示例
2020/05/18 PHP
jquery checkbox全选、取消全选实现代码
2010/03/05 Javascript
JQuery在页面中添加和除移DOM示例代码
2013/06/24 Javascript
avascript中的自执行匿名函数应用示例
2014/09/15 Javascript
什么是 AngularJS?AngularJS简介
2014/12/06 Javascript
浅谈javascript中call()、apply()、bind()的用法
2015/04/20 Javascript
JS实现来回出现文字的状态栏特效代码
2015/10/31 Javascript
jQuery头像裁剪工具jcrop用法实例(附演示与demo源码下载)
2016/01/22 Javascript
JQuery+EasyUI轻松实现步骤条效果
2016/02/22 Javascript
jQuery实现字符串全部替换的方法
2016/12/12 Javascript
详解Node.js串行化流程控制
2017/05/04 Javascript
JS隐藏号码中间4位代码实例
2019/04/09 Javascript
详解Vue路由自动注入实践
2019/04/17 Javascript
Element-ui中元素滚动时el-option超出元素区域的问题
2019/05/30 Javascript
详解vue页面首次加载缓慢原因及解决方案
2019/11/06 Javascript
vue中父子组件传值,解决钩子函数mounted只运行一次的操作
2020/07/27 Javascript
vue任意关系组件通信与跨组件监听状态vue-communication
2020/10/18 Javascript
Python中声明只包含一个元素的元组数据方法
2014/08/25 Python
关于Python Tkinter Button控件command传参问题的解决方式
2020/03/04 Python
keras 简单 lstm实例(基于one-hot编码)
2020/07/02 Python
python matplotlib工具栏源码探析二之添加、删除内置工具项的案例
2021/02/25 Python
香港优质食材和美酒专门店:FoodWise
2017/09/01 全球购物
New Balance澳大利亚官网:运动鞋和健身服装
2019/02/23 全球购物
Chain Reaction Cycles俄罗斯:世界上最大的在线自行车商店
2019/08/27 全球购物
2013的个人自我评价
2013/12/26 职场文书
运动会广播稿诗歌版
2014/09/12 职场文书
离婚协议书的书写要求
2014/09/17 职场文书
家长会后的感想
2015/08/11 职场文书
python实现ROA算子边缘检测算法
2021/04/05 Python
python识别围棋定位棋盘位置
2021/07/26 Python