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中实现从目录中过滤出指定文件类型的文件
Feb 02 Python
简单掌握Python中glob模块查找文件路径的用法
Jul 05 Python
Python 通过URL打开图片实例详解
Jun 01 Python
详解tensorflow训练自己的数据集实现CNN图像分类
Feb 07 Python
对TensorFlow中的variables_to_restore函数详解
Jul 30 Python
使用11行Python代码盗取了室友的U盘内容
Oct 23 Python
centos6.5安装python3.7.1之后无法使用pip的解决方案
Feb 14 Python
python浪漫表白源码
Apr 05 Python
Python  Django 母版和继承解析
Aug 09 Python
Pytorch加载部分预训练模型的参数实例
Aug 18 Python
6行Python代码实现进度条效果(Progress、tqdm、alive-progress​​​​​​​和PySimpleGUI库)
Jan 06 Python
python利用pandas分析学生期末成绩实例代码
Jul 09 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
espresso double下 咖啡粉超细时 饼压力对咖啡的影响
2021/03/03 冲泡冲煮
php while循环得到循环次数
2013/10/26 PHP
php代码检查代理ip的有效性
2016/08/19 PHP
php curl批处理实现可控并发异步操作示例
2018/05/09 PHP
ThinkPHP5.1验证码功能实现的示例代码
2020/06/08 PHP
动态添加js事件实现代码
2009/03/12 Javascript
jQuery库与其他JS库冲突的解决办法
2010/02/07 Javascript
JSON 教程 json入门学习笔记
2020/09/22 Javascript
基于jQuery的Spin Button自定义文本框数值自增或自减
2010/07/17 Javascript
jQuery validate 中文API 附validate.js中文api手册
2010/07/31 Javascript
json的前台操作和后台操作实现代码
2012/01/20 Javascript
javascript轻松实现当鼠标移开时已弹出子菜单自动消失
2013/12/29 Javascript
node.js中的fs.stat方法使用说明
2014/12/16 Javascript
jquery+ajax实现直接提交表单实例分析
2016/06/17 Javascript
如何判断出一个js对象是否一个dom对象
2016/11/24 Javascript
nodejs+websocket实时聊天系统改进版
2017/05/18 NodeJs
jquery根据name取得select选中的值实例(超简单)
2018/01/25 jQuery
JavaScript函数apply()和call()用法与异同分析
2018/08/10 Javascript
JS 遍历 json 和 JQuery 遍历json操作完整示例
2019/11/11 jQuery
Vue Router的手写实现方法实现
2020/03/02 Javascript
[03:45]Newbee战队出征西雅图 决战2016国际邀请赛
2016/08/02 DOTA
使用python检测手机QQ在线状态的脚本代码
2013/02/10 Python
python实现文件分组复制到不同目录的例子
2014/06/04 Python
以一段代码为实例快速入门Python2.7
2015/03/31 Python
Python中为什么要用self探讨
2015/04/14 Python
浅谈PyQt5 的帮助文档查找方法,可以查看每个类的方法
2019/06/25 Python
浅谈django url请求与数据库连接池的共享问题
2019/08/29 Python
HTML5之多线程(Web Worker)
2019/01/02 HTML / CSS
什么是表空间(tablespace)和系统表空间(System tablespace)
2013/02/25 面试题
化工专业推荐信范文
2013/11/28 职场文书
商务英语专业求职信范文
2014/01/28 职场文书
八项规定整改方案
2014/02/21 职场文书
企业财务经理岗位职责
2015/04/08 职场文书
能让Python提速超40倍的神器Cython详解
2021/06/24 Python
实操Python爬取觅知网素材图片示例
2021/11/27 Python
使用Oracle命令进行数据库备份与还原
2021/12/06 Oracle