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中的异常处理简明介绍
Apr 13 Python
在Django的视图(View)外使用Session的方法
Jul 23 Python
python如何通过protobuf实现rpc
Mar 06 Python
Python编码类型转换方法详解
Jul 01 Python
python3 遍历删除特定后缀名文件的方法
Apr 23 Python
举例讲解Python常用模块
Mar 08 Python
Python基础之函数的定义与使用示例
Mar 23 Python
详解Python 函数如何重载?
Apr 23 Python
Python集成开发工具Pycharm的安装和使用详解
Mar 18 Python
在django中form的label和verbose name的区别说明
May 20 Python
Python基于字典实现switch case函数调用
Jul 22 Python
Python pip 常用命令汇总
Oct 19 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原理之变量(Variables inside PHP)
2013/08/09 PHP
php生成随机密码自定义函数代码(简单快速)
2014/05/10 PHP
CentOS下与Apache连接的PHP多版本共存方案实现详解
2015/12/19 PHP
PHP实现的同步推荐操作API接口案例分析
2016/11/30 PHP
基于ThinkPHP5.0实现图片上传插件
2017/09/25 PHP
简单的JS多重继承示例
2008/03/13 Javascript
JavaScript动态调整TextArea高度的代码
2010/12/28 Javascript
node.js中的fs.close方法使用说明
2014/12/17 Javascript
JS实现横向与竖向两个选项卡Tab联动的方法
2015/09/27 Javascript
基于JavaScript实现移除(删除)数组中指定元素
2016/01/04 Javascript
动态生成的DOM不会触发onclick事件的原因及解决方法
2016/08/06 Javascript
JS如何生成一个不重复的ID的函数
2016/12/25 Javascript
Vue组件之自定义事件的功能图解
2018/02/01 Javascript
获取layer.open弹出层的返回值方法
2018/08/20 Javascript
详解easyui 切换主题皮肤
2019/04/04 Javascript
详解element-ui中el-select的默认选择项问题
2019/08/02 Javascript
vue项目中使用AES实现密码加密解密(ECB和CBC两种模式)
2019/08/12 Javascript
基于JS实现父组件的请求服务过程解析
2019/10/14 Javascript
vue:el-input输入时限制输入的类型操作
2020/08/05 Javascript
[50:17]Newbee vs Serenity 2018国际邀请赛小组赛BO2 第二场 8.17
2018/08/18 DOTA
更换Django默认的模板引擎为jinja2的实现方法
2018/05/28 Python
Numpy array数据的增、删、改、查实例
2018/06/04 Python
Pandas:Series和DataFrame删除指定轴上数据的方法
2018/11/10 Python
python中的decimal类型转换实例详解
2019/06/26 Python
python调试神器PySnooper的使用
2019/07/03 Python
python boto和boto3操作bucket的示例
2020/10/30 Python
python爬虫利器之requests库的用法(超全面的爬取网页案例)
2020/12/17 Python
HolidayLettings英国:预订最好的度假公寓、别墅和自助式住宿
2019/08/27 全球购物
美国伴娘礼服商店:Evening Collective
2019/10/07 全球购物
电信专业应届生自荐信
2013/09/28 职场文书
大学生职业生涯规划书范文
2014/01/04 职场文书
服装采购员岗位职责
2014/03/15 职场文书
节水口号标语
2014/06/19 职场文书
圣诞晚会主持词
2015/07/01 职场文书
JS的深浅复制详细
2021/10/16 Javascript
HTML页面中使两个div并排显示的实现
2022/05/15 HTML / CSS