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使用WMI检测windows系统信息、硬盘信息、网卡信息的方法
May 15 Python
Python之py2exe打包工具详解
Jun 14 Python
Python正确重载运算符的方法示例详解
Aug 27 Python
基于Python os模块常用命令介绍
Nov 03 Python
使用Python的toolz库开始函数式编程的方法
Nov 15 Python
python保存二维数组到txt文件中的方法
Nov 15 Python
PyCharm-错误-找不到指定文件python.exe的解决方法
Jul 01 Python
基于python的BP神经网络及异或实现过程解析
Sep 30 Python
Python3爬虫里关于代理的设置总结
Jul 30 Python
Python中的None与 NULL(即空字符)的区别详解
Sep 24 Python
详解Django自定义图片和文件上传路径(upload_to)的2种方式
Dec 01 Python
opencv-python图像配准(匹配和叠加)的实现
Jun 23 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
PHP和XSS跨站攻击的防范
2007/04/17 PHP
php常用Stream函数集介绍
2013/06/24 PHP
通过代码实例解析PHP session工作原理
2020/12/11 PHP
JavaScript 利用StringBuffer类提升+=拼接字符串效率
2009/11/24 Javascript
写JQuery插件的基本知识
2013/11/25 Javascript
jquery使用jquery.zclip插件复制对象的实例教程
2013/12/04 Javascript
jquery动态加载select下拉框示例代码
2013/12/10 Javascript
jquery实现表单验证简单实例演示
2015/11/23 Javascript
Javascript实现鼠标框选操作  不是点击选取
2016/04/14 Javascript
nodejs学习笔记之路由
2017/03/27 NodeJs
js制作简单的音乐播放器的示例代码
2017/08/28 Javascript
vue axios 给生产环境和发布环境配置不同的接口地址(推荐)
2018/05/08 Javascript
前端面试知识点目录一览
2019/04/15 Javascript
微信小程序的线程架构【推荐】
2019/05/14 Javascript
vue使用swiper实现中间大两边小的轮播图效果
2019/11/24 Javascript
three.js利用卷积法如何实现物体描边效果
2019/11/27 Javascript
卸载vue2.0并升级vue_cli3.0的实例讲解
2020/02/16 Javascript
vue.js中使用微信扫一扫解决invalid signature问题(完美解决)
2020/04/11 Javascript
[40:01]OG vs Winstrike 2018国际邀请赛小组赛BO2 第一场 8.19
2018/08/21 DOTA
python进阶教程之函数参数的多种传递方法
2014/08/30 Python
Python中用于检查英文字母大写的isupper()方法
2015/05/19 Python
python3使用requests模块爬取页面内容的实战演练
2017/09/25 Python
python实现文本界面网络聊天室
2018/12/12 Python
在python中用print()输出多个格式化参数的方法
2019/07/16 Python
10行Python代码计算汽车数量的实现方法
2019/10/23 Python
python读取tif图片时保留其16bit的编码格式实例
2020/01/13 Python
Python底层封装实现方法详解
2020/01/22 Python
Python实现PS滤镜中的USM锐化效果
2020/12/04 Python
CSS3实现苹果手机解锁的字体闪亮效果示例
2021/01/05 HTML / CSS
澳大利亚优惠网站:Deals.com.au
2019/07/02 全球购物
优良学风班总结材料
2014/02/08 职场文书
十八届三中全会报告学习材料
2014/02/17 职场文书
给老婆大人的检讨书
2014/02/24 职场文书
学习教师法的心得体会
2014/09/03 职场文书
新员工入职感言范文!
2019/07/04 职场文书
利用Python网络爬虫爬取各大音乐评论的代码
2021/04/13 Python