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 相关文章推荐
Win7上搭建Cocos2d-x 3.1.1开发环境
Jul 03 Python
如何使用python爬取csdn博客访问量
Feb 14 Python
python自制包并用pip免提交到pypi仅安装到本机【推荐】
Jun 03 Python
基于Python安装pyecharts所遇的问题及解决方法
Aug 12 Python
Python如何基于smtplib发不同格式的邮件
Dec 30 Python
Python socket聊天脚本代码实例
Jan 02 Python
python实现文法左递归的消除方法
May 22 Python
利用PyTorch实现VGG16教程
Jun 24 Python
python如何写try语句
Jul 14 Python
Python 使用双重循环打印图形菱形操作
Aug 09 Python
解决pycharm修改代码后第一次运行不生效的问题
Feb 06 Python
python游戏开发之pygame实现接球小游戏
Apr 22 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
php4的彩蛋
2006/10/09 PHP
php分页代码学习示例分享
2014/02/20 PHP
MyEclipse常用配置图文教程
2014/09/11 PHP
php更新mysql后获取改变行数的方法
2014/12/25 PHP
mod_php、FastCGI、PHP-FPM等PHP运行方式对比
2015/07/02 PHP
laravel5环境隐藏index.php后缀(apache)的方法
2019/10/12 PHP
jquery获取颜色在ie和ff下的区别示例介绍
2014/03/28 Javascript
jQuery 插件开发指南
2014/11/14 Javascript
浅谈javascript面向对象程序设计
2015/01/21 Javascript
js实现仿百度汽车频道选择汽车图片展示实例
2015/05/06 Javascript
JS动态日期时间的获取方法
2015/09/28 Javascript
jQuery实现TAB选项卡切换特效简单演示
2016/03/04 Javascript
vue2.0安装style/css loader的方法
2018/03/14 Javascript
vue-cli项目中使用Mockjs详解
2018/05/14 Javascript
原生JS实现简单的倒计时功能示例
2018/08/30 Javascript
详解vue开发中调用微信jssdk的问题
2019/04/16 Javascript
koa+mongoose实现简单增删改查接口的示例代码
2019/05/13 Javascript
vue实现动态给id赋值,点击事件获取当前点击的元素的id操作
2020/11/09 Javascript
Python魔术方法详解
2015/02/14 Python
python 自动化将markdown文件转成html文件的方法
2016/09/23 Python
python 基础教程之Map使用方法
2017/01/17 Python
详解Python3操作Mongodb简明易懂教程
2017/05/25 Python
Python实现的中国剩余定理算法示例
2017/08/05 Python
selenium python浏览器多窗口处理代码示例
2018/01/15 Python
彻底搞懂 python 中文乱码问题(深入分析)
2020/02/28 Python
Python使用re模块验证危险字符
2020/05/21 Python
英国家电购物网站:Sonic Direct
2019/03/26 全球购物
FirstCry阿联酋儿童和婴儿产品网上购物:FirstCry.ae
2021/02/22 全球购物
为什么需要版本控制
2016/10/28 面试题
物流创业计划书
2014/02/01 职场文书
大学生创业项目方案
2014/03/08 职场文书
新闻工作者先进事迹
2014/05/26 职场文书
县政府班子个人对照检查材料
2014/10/05 职场文书
门球健将观后感
2015/06/16 职场文书
pytorch交叉熵损失函数的weight参数的使用
2021/05/24 Python