python学习(二):python对SQLite数据库的基本操作

一、环境

        python版本:Python 3.6.8

        sqlite版本:windows下的  SQLite version 3.25.2

        操作系统:win10

二、SQLite简单介绍

        SQLite是一个进程内的库,实现了自给自足的、无服务器的、零配置的、事务性的 SQL 数据库引擎。它是一个零配置的数据库,这意味着与其他数据库一样,您不需要在系统中配置。

       SQLite使用起来非常方便,在windows下,SQLite不需要安装,可以直接使用,不依赖其他任何软件,只需要在一个文件夹中有如下文件即可:

sqldiff.exe
sqlite3.dll
sqlite3.exe
sqlite3_analyzer.exe

迁移起来很方便,直接将数据库实例文件和以上四个文件复制到令一个电脑上就能用了;

三、SQLite命令表

        sqlite命令可以直接从命令帮助中获得,在cmd中输入如下命令:

(venv) D:\pythonstudy\lottery\db>sqlite3.exe
SQLite version 3.25.2 2018-09-25 19:08:10
Enter ".help" for usage hints.
Connected to a transient in-memory database.
Use ".open FILENAME" to reopen on a persistent database.
sqlite> .help
命令 描述
.backup ?DB? FILE 备份 DB 数据库(默认是 "main")到 FILE 文件。
.bail ON|OFF 发生错误后停止。默认为 OFF。
.databases 列出数据库的名称及其所依附的文件。
.dump ?TABLE? 以 SQL 文本格式转储数据库。如果指定了 TABLE 表,则只转储匹配 LIKE 模式的 TABLE 表。
.echo ON|OFF 开启或关闭 echo 命令。
.exit 退出 SQLite 提示符。
.explain ON|OFF 开启或关闭适合于 EXPLAIN 的输出模式。如果没有带参数,则为 EXPLAIN on,及开启 EXPLAIN。
.header(s) ON|OFF 开启或关闭头部显示。
.help 显示消息。
.import FILE TABLE 导入来自 FILE 文件的数据到 TABLE 表中。
.indices ?TABLE? 显示所有索引的名称。如果指定了 TABLE 表,则只显示匹配 LIKE 模式的 TABLE 表的索引。
.load FILE ?ENTRY? 加载一个扩展库。
.log FILE|off 开启或关闭日志。FILE 文件可以是 stderr(标准错误)/stdout(标准输出)。
.mode MODE 设置输出模式,MODE 可以是下列之一:
  • csv 逗号分隔的值

  • column 左对齐的列

  • html HTML 的 <table> 代码

  • insert TABLE 表的 SQL 插入(insert)语句

  • line 每行一个值

  • list 由 .separator 字符串分隔的值

  • tabs 由 Tab 分隔的值

  • tcl TCL 列表元素

.nullvalue STRING 在 NULL 值的地方输出 STRING 字符串。
.output FILENAME 发送输出到 FILENAME 文件。
.output stdout 发送输出到屏幕。
.print STRING... 逐字地输出 STRING 字符串。
.prompt MAIN CONTINUE 替换标准提示符。
.quit 退出 SQLite 提示符。
.read FILENAME 执行 FILENAME 文件中的 SQL。
.schema ?TABLE? 显示 CREATE 语句。如果指定了 TABLE 表,则只显示匹配 LIKE 模式的 TABLE 表。
.separator STRING 改变输出模式和 .import 所使用的分隔符。
.show 显示各种设置的当前值。
.stats ON|OFF 开启或关闭统计。
.tables ?PATTERN? 列出匹配 LIKE 模式的表的名称。
.timeout MS 尝试打开锁定的表 MS 毫秒。
.width NUM NUM 为 "column" 模式设置列宽度。
.timer ON|OFF 开启或关闭 CPU 定时器。

四、python对SQLite的增、删、改、查

1.操作准备:将第二节中的四个文件复制到一个单独的文件夹中,在当前文件夹中打开cmd窗口(按住shift+鼠标右键),使用如下命令创建测试数据库,下面的命令会在当前的文件夹中创建testdb.db数据库文件;

F:\bokeses\sqlite>sqlite3.exe testdb.db
SQLite version 3.25.2 2018-09-25 19:08:10
Enter ".help" for usage hints.
sqlite> .q

2.使用python连接sqlite数据库(代码文件命名为:sqlitetest.py)

#coding = utf-8
import sqlite3

def testconn():
    connstr = './testdb.db'
    try:
        conn = sqlite3.connect(connstr)
        print('ok')
    except Exception as e :
        print(e)

if __name__ == "__main__":
    testconn()

3.创建数据表:

#coding = utf-8
import sqlite3

def testcreatetable():
    connstr = './testdb.db'
    try:
        conn = sqlite3.connect(connstr)
        cursor = conn.cursor()
        sql = "CREATE TABLE TESTDB (ID INT,NAME CHAR,AGE INT,BZ CHAR)"
        cursor.execute(sql)
        conn.commit()
        cursor.close()
        conn.close()
        print('ok')
    except Exception as e :
        print(e)
if __name__ == "__main__":
    testcreatetable()

执行结果:

PS F:\bokeses\sqlite> python sqlitetest.py
ok

在cmd中使用如下命令验证数据库表是否存在:

F:\bokeses\sqlite>sqlite3.exe testdb.db
SQLite version 3.25.2 2018-09-25 19:08:10
Enter ".help" for usage hints.
sqlite> .tables
TESTDB
sqlite> .schema TESTDB
CREATE TABLE TESTDB (ID INT,NAME CHAR,AGE INT,BZ CHAR);
sqlite>

4.插入一条数据条目:

#coding = utf-8
import sqlite3

def testinsertdb():
    connstr = "./testdb.db"
    try:
        conn = sqlite3.connect(connstr)
        cursor = conn.cursor()
        sql = "INSERT INTO TESTDB (ID,NAME,AGE,BZ) VALUES (1,'XZP',25,'HE IS A BEGINNER')"
        cursor.execute(sql)
        conn.commit()
        cursor.close()
        conn.close()
        print("数据表插入成功")
    except Exception as e :
        print(e)
if __name__ == "__main__":
    testinsertdb()

执行结果:

F:\bokeses\sqlite>python sqlitetest.py
数据表插入成功

5.查询数据条目:

#coding = utf-8
import sqlite3


def testselectdb():
    connstr = "./testdb.db"
    try:
        conn = sqlite3.connect(connstr)
        cursor = conn.cursor()
        sql = "SELECT * FROM TESTDB"
        cursor.execute(sql)
        r = cursor.fetchone()
        columns = cursor.description
        
        for item in range(len(columns)):
            print("column:%s    value:%s" %(columns[item][0],r[item]))
        cursor.close()
        conn.close()

    except Exception as e :
        print(e)
if __name__ == "__main__":
    testselectdb()

运行结果如下:

F:\bokeses\sqlite>python sqlitetest.py
column:ID    value:1
column:NAME    value:XZP
column:AGE    value:25
column:BZ    value:HE IS A BEGINNER

F:\bokeses\sqlite>

6.删除条目

#coding = utf-8
import sqlite3

def testdeleteitem():
    connstr = "./testdb.db"
    try:
        conn = sqlite3.connect(connstr)
        cursor = conn.cursor()
        sql = "delete FROM TESTDB"
        cursor.execute(sql)
        conn.commit()
        cursor.close()
        conn.close()
        print("删除表中数据完成!")
    except Exception as e :
        print(e)
if __name__ == "__main__":
    testdeleteitem()

运行结果:

F:\bokeses\sqlite>python sqlitetest.py
删除表中数据完成!

F:\bokeses\sqlite>

五、自己封装的简单的python操作SQLite的工具库

#coding=utf-8

#Name:sqlite3DBHelper
#Description:
#Date:2019/2/24
#Author:xzp

import sqlite3

class sqlite3Helper():
    def __init__(self,constr):
        self.conStr = constr

    def getconn(self):
        '''
        get a connection
        :return: 
        '''
        try:
            conn = sqlite3.connect(self.conStr)
            return conn
        except Exception as e:
            raise e
    def executeNoQuery(self,sql):
        '''
        only execute sql
        :param sql: 
        :return: 
        '''
        try:
            conn = self.getconn()
            cursor = conn.cursor()
            cursor.execute(sql)
            cursor.close()
            conn.commit()
            conn.close()
        except Exception as e:
            raise e
    def executeNoQueryparameter(self,sql,parameter):
        '''
        execute the sql that contains parameter
        :param sql: 
        :param parameter: the sql parameter dictionary
        :return: 
        '''
        try:
            conn = self.getconn()
            cursor = conn.cursor()
            cursor.execute(sql,parameter)
            conn.commit()
            cursor.close()
            conn.close()
        except Exception as e:
            raise e
    def executeAdapter(self,sql):
        '''
        execute the query by sql
        :param sql: 
        :return: return the result list
        '''
        try:
            r = []
            conn = self.getconn()
            cursor = conn.cursor()
            cursor.execute(sql)
            for i in cursor:
                r.append(list(i))
            cursor.close()
            conn.close()
            return r
        except Exception as e:
            raise e
        
    def releaseconn(self,conn):
        '''
        close the connection
        :param conn: 
        :return: 
        '''
        try:
            conn.close()
        except Exception as e:
            raise e

slatehelper = sqlite3Helper('./db/eleselectfive.db')

if __name__ == '__main__':
    r = slatehelper.executeAdapter('SELECT * FROM elevenfive')
    print(r)

六、实操项目

        自己在空闲之余写了点小东西,自己分析玩一下,觉得挺有意思,拿出来和大家分享下:

        下面这个项目主要实现了从某网站上面爬取十一选五的彩票号码,并将彩票号码存储到sqlite数据库中,通过将近10期号码与历史中连续10期彩票号码进行距离求和运算,得出最小距离拟合的曲线,以最小距离的10期号码的下一期号码作为参照,预测即将开奖的下一期彩票号码;下面献上代码:

百度网盘:https://pan.baidu.com/s/1XwzTLkfL3_fFNfB3L1k_6A   提取码:ivbq

文件有密码,真的需要的朋友请留言邮箱~~~

发布了21 篇原创文章 · 获赞 17 · 访问量 5万+

猜你喜欢

转载自blog.csdn.net/xiazhipeng1000/article/details/89295281
今日推荐