Python 操作SQLite数据库详情

目录
  • 一、简单操作SQLite数据库
    • 1、简单的插入语句的使用
    • 2、简单的查询语句的使用
  • 二、更新数据与删除
  • 三、实现用户名密码验证
  • 四、SQLite检索时间记录
  • 五、SQLite提取数据并绘图

前言:

SQLite属于轻型数据库,遵守ACID的关系型数据库管理系统,它包含在一个相对小的C库中。在很多嵌入式产品中使用了它,它占用资源非常的低,python 中默认继承了操作此款数据库的引擎 sqlite3 说是引擎不如说就是数据库的封装版,开发自用小程序的使用使用它真的大赞

一、简单操作SQLite数据库

简单操作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)        # 执行创建表操作

1、简单的插入语句的使用

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)

2、简单的查询语句的使用

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()

三、实现用户名密码验证

当用户输入错误密码后,自动锁定该用户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")
    print(temp)

五、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()

到此这篇关于Python 操作SQLite数据库详情的文章就介绍到这了,更多相关Python 操作SQLite数据库内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!

(0)

相关推荐

  • Python 如何操作 SQLite 数据库

    写在之前 SQLite 是一个小型的关系型数据库,它最大的特点在于不需要单独的服务.零配置.我们在之前讲过的两个数据库,不管是 MySQL 还是 MongoDB,都需要我们安装.安装之后,然后运行起来,其实这就相当于已经有一个相应的服务在跑着. SQLite 与前面所说的两个数据库不同.首先Python 已经将相应的驱动模块作为了标准库的一部分,只要是你安装了 Python,就可以使用:再者它可以类似于操作文件那样来操作 SQLite 数据库文件.还有一点,SQLite 源代码不受版权限制. 建

  • Python操作SQLite数据库过程解析

    SQLite是一款轻型的数据库,是遵守ACID的关系型数据库管理系统. 不像常见的客户-服务器范例,SQLite引擎不是个程序与之通信的独立进程,而是连接到程序中成为它的一个主要部分.所以主要的通信协议是在编程语言内的直接API调用. Python标准库包含一个SQLite包装器:使用模块sqlite3实现的PySQLite. 下面是一个操作SQLite数据库的例子:创建表.插入记录.查询记录. import sqlite3 #创建直接到数据库文件的连接,如果文件不存在则自动创建 conn =

  • python 操作sqlite数据库的方法

    目录 前言 简单介绍 创建或连接数据库 游标 创建表 插入 查询 查询总数 查询所有 查询第一条 分页查询 更新 删除 总结 前言 sqlite的官网 sqlite.org/index.html SQLite作为一个SQL数据库引擎,是由C语言实现的,又小又快,具有高可靠性且功能齐全. 作为嵌入式数据库,在移动设备中使用非常广泛且方便.Python3中内嵌了sqlite的驱动,我们直接导入就行. import sqlite3 简单介绍 首先我们给大家一个能够运行的Python程序,让大家对Pyt

  • Python操作SQLite/MySQL/LMDB数据库的方法

    1.概述 1.1前言 最近在存储字模图像集的时候,需要学习LMDB,趁此机会复习了SQLite和MySQL的使用,一起整理在此. 1.2环境 使用win7,Python 3.5.2. 2.SQLite 2.1准备 SQLite是一种嵌入式数据库,它的数据库就是一个文件.Python 2.5x以上版本内置了SQLite3,使用时直接import sqlite3即可. 2.2操作流程 概括地讲,操作SQLite的流程是: ·通过sqlite3.open()创建与数据库文件的连接对象connectio

  • Python连接SQLite数据库并进行增册改查操作方法详解

    SQLite简介 SQLite,是一款轻型的数据库,是遵守ACID的关系型数据库管理系统,它包含在一个相对小的C库中.它是D.RichardHipp建立的公有领域项目.它的设计目标是嵌入式的,而且目前已经在很多嵌入式产品中使用了它,它占用资源非常的低,在嵌入式设备中,可能只需要几百K的内存就够了.它能够支持Windows/Linux/Unix等等主流的操作系统,同时能够跟很多程序语言相结合,比如 Tcl.C#.PHP.Java等,还有ODBC接口,同样比起Mysql.PostgreSQL这两款开

  • Python 操作SQLite数据库详情

    目录 一.简单操作SQLite数据库 1.简单的插入语句的使用 2.简单的查询语句的使用 二.更新数据与删除 三.实现用户名密码验证 四.SQLite检索时间记录 五.SQLite提取数据并绘图 前言: SQLite属于轻型数据库,遵守ACID的关系型数据库管理系统,它包含在一个相对小的C库中.在很多嵌入式产品中使用了它,它占用资源非常的低,python 中默认继承了操作此款数据库的引擎 sqlite3 说是引擎不如说就是数据库的封装版,开发自用小程序的使用使用它真的大赞 一.简单操作SQLit

  • Python操作SQLite数据库的方法详解

    本文实例讲述了Python操作SQLite数据库的方法.分享给大家供大家参考,具体如下: SQLite简单介绍 SQLite数据库是一款非常小巧的嵌入式开源数据库软件,也就是说没有独立的维护进程,所有的维护都来自于程序本身.它是遵守ACID的关联式数据库管理系统,它的设计目标是嵌入式的,而且目前已经在很多嵌入式产品中使用了它,它占用资源非常的低,在嵌入式设备中,可能只需要几百K的内存就够了.它能够支持Windows/Linux/Unix等等主流的操作系统,同时能够跟很多程序语言相结合,比如 Tc

  • Python操作SQLite数据库的方法详解【导入,创建,游标,增删改查等】

    本文实例讲述了Python操作SQLite数据库的方法.分享给大家供大家参考,具体如下: SQLite简介 SQLite,是一款轻型的数据库,是遵守ACID的关系型数据库管理系统,它包含在一个相对小的C库中.它是D.RichardHipp建立的公有领域项目.它的设计目标是嵌入式的,而且目前已经在很多嵌入式产品中使用了它,它占用资源非常的低,在嵌入式设备中,可能只需要几百K的内存就够了.它能够支持Windows/Linux/Unix等等主流的操作系统,同时能够跟很多程序语言相结合,比如 Tcl.C

  • Python 操作SQLite数据库的示例

    SQLite,是一款轻型的数据库,是遵守ACID的关系型数据库管理系统,它包含在一个相对小的C库中.在很多嵌入式产品中使用了它,它占用资源非常的低,python 中默认继承了操作此款数据库的引擎 sqlite3 说是引擎不如说就是数据库的封装版,开发自用小程序的使用使用它真的大赞 简单操作SQLite数据库:创建 sqlite数据库是一个轻量级的数据库服务器,该模块默认集成在python中,开发小应用很不错. import sqlite3 # 数据表的创建 conn = sqlite3.conn

  • python 操作 mongodb 数据库详情

    目录 一.安装 二.连接数据库 三.创建数据库 四.所有数据库 五.创建集合 六.插入数据 七.查询数据 八.高级查询 九.count统计 十.修改数据 十一.删除数据 十二.数据排序 一.安装 pip install pymongo 二.连接数据库 import pymongo # 方式一 client = pymongo.MongoClient('mongodb://localhost:27017') # 方式二 client = pymongo.MongoClient('localhost

  • 利用python操作SQLite数据库及文件操作详解

    前言 最近在工作中遇到一个需求,就是要把SQLite数据中没有存储的文件名的文件删除掉,想来想去还是决定用python.所以也就花了一天半的时间学习了下,随手写了个小例子,下面话不多说了,感兴趣的朋友们一起来看看详细的介绍吧. 直接上代码 要用到的头文件包 #coding=utf-8 #!/usr/bin/python #!/usr/bin/env python import os import shutil import sqlite3 定义记录变量 #记录所文件数 sumCount=0; #

随机推荐