Home  >  Article  >  Backend Development  >  An in-depth chat about the sqlite3 database in Python

An in-depth chat about the sqlite3 database in Python

青灯夜游
青灯夜游forward
2022-11-11 18:30:102118browse

An in-depth chat about the sqlite3 database in Python

sqlite3 database

An in-depth chat about the sqlite3 database in Python

sqlite3 database is Python’s own database, even is not needed Additional installation module , and the operation is simple.

Python Mysql = SQLite

An in-depth chat about the sqlite3 database in Python

An in-depth chat about the sqlite3 database in Python

But there are very few tutorials on this kind of database on the Internet, because I only recently I know, so I have been looking for information for a long time.

Finally found it today. Let me summarize it. I’ve been looking for it for a long time

1. The required module (only one)

import sqlite3

2. How to use the module

First open us Compiler (vscode is recommended, because the database file suffix is ​​.db, and the display is clearer in vscode)

2.1 Create a connection with the database

Put the code first

conn = sqlite3.connect('test.db')

Use sqlite3's connect function to create a database or connect to a database,

if the database exists , just connect to this database,

If this library does not exist, create the database.

The parentheses on the right are the database names.

We save this in the variable conn. You can name this variable by yourself

Formula:

变量名 = sqlite3.connect( '你要的数据库名.db' )

2.2 Create a cursor

Or put the code first

cur = conn.cursor()

In 2.1, we created a connection to the database, and we now need a CursorTo execute sql commands,

So we have to create a cursor using the cursor function of conn.

conn is the variable created in 2.1 just now to save the database. You need to use the variable name you defined, and

define another variable to represent this cursor.

Formula:

变量 = 数据库变量.cursor()

2.3 Create table

Put the code first

import sqlite3
def check(db_name,table_name):
    conn = sqlite3.connect(db_name)
    cursor = conn.cursor()
    sql = '''SELECT tbl_name FROM sqlite_master WHERE type = 'table' '''
    cursor.execute(sql)
    values = cursor.fetchall()
    tables = []
    for v in values:
        tables.append(v[0])
    if table_name not in tables:
        return False # 可以建表
    else:
        return True # 不能建表
conn = sqlite3.connect('数据库名.db')
#创建一个游标 cursor
cur = conn.cursor()
if (check("数据库名.db","Table名") == False):
    sql_text_1 = '''CREATE TABLE 你的table名
            (xx XX,
                xx XX);'''
    # 执行sql语句
    cur.execute(sql_text_1)

The code is relatively long, because I also added the two lines of code 2.1 and 2.2 Go up.

We need a table (table) to store data. The code to create a table is as follows:

变量名 = '''CREATE TABLE 你的table名
            (xx XX,
                xx XX);'''
# 执行sql语句
cur.execute(上面的变量名)

The above uses a variable to save the sql statement to create the table.

The following uses The cur (that's the cursor just now).execute() function executes the statement that creates the table.

We can also use the cur.executemany function to execute multiple sql statements at the same time.

The content of the sql statement, for example, the format of creating a table is as above

Format: ' ' 'CREATE TABLE your table name (xx XX, xx XX) ;' ' '

The lowercase xx in this line of code is the attribute name you want. For example, your database is like this

Name Class
张三 1

其中,属性名就是 “姓名” 和 “班级”,

小写的 xx 就应该分别写姓名和班级(注意,不带引号)

后面的大写的XX就是这个属性所接受的数据的类型,

就相当于Python中的 int 类型和 str 类型。

只不过,我们在 sql 语句中,把 int 类型改成了 NUMBER,把 str 类型改成了 TEXT

当我们运行这个代码,我们的文件夹目录里会多出来一个 你的数据库名.db 文件

当我们再次运行,会发现程序报错了。

报错信息的大概意思是:table 已经存在了。

这是因为我们第一次运行时已经创建了 table ,我们再次运行时,

程序会再次创建同名 table,就会报错。

所以,我们创建 table 之前要判断一下这个table存不存在,如果存在就不创建,如果不存在就创建

这个判断我把它写成了一个函数,就是我上面代码那个 check 函数。

这一步也是我想了好长时间,还找资料找了好长时间才知道的

2.4插入数据

先放代码

cur.executemany('INSERT INTO 你的table名 VALUES (?,?)', data)
conn.commit()

其中第一行代码中 executemany() 函数的意思就是同时执行多个 sql 语句。

这个函数的括号里写的逗号前面就是插入数据的 sql 语句,后面 data 可以是一个列表或者元组。注意,如果是列表的话,必须是列表里面有若干个元组的形式。

插入数据的 sql 语句的使用:

INSERT INTO 你的table名 VALUES (若干个逗号,用逗号分割)

这里我们要插入 data 这些数据,所以在括号里我们使用问号 “?” 来代替这个元素。

大家可以回去看一下 2.3 创建table 的讲解,在2.3中,我们创建了两个属性,分别是 “姓名” 和 “班级”。因为我们有两个属性,所以要有两个问号。

2.5查找数据

先放代码

def find_tb():
    cur.execute("select * from 你的table名")
    # 提取查询到的数据
    return cur.fetchall()

这个就很简单了,我写这个函数使用时可以把你那个table里的所有数据都取出来。

第一行是查找table的 sql 语句,格式是:

select * from 你的table名

下一行再用 fetchall() 函数把数据提取出来,直接 return 即可。

快乐的coding时间!

好了,前面的东西大家应该也都看完了,来点 demo ?

顺便说一下,我这个 demo 的灵感来源是最近在网上刷到很多高考查分的视频,恰好最近在做这个数据库,所以说我这个 demo 受考试的启发,就做了一个学生分数系统,其实这个特别爽,可以把自己的分数改成全部满分!虽然实际没啥用,但是还是很爽的

代码里没有我没讲过的部分,大家可以对照上面的讲解看代码,VScode无报错运行。

对了,如果有看不懂的可以私信我,不出意外的话一天之内就能回复。

代码:

import sqlite3
import os
def check(db_name,table_name):
    conn = sqlite3.connect(db_name)
    cursor = conn.cursor()
    sql = '''SELECT tbl_name FROM sqlite_master WHERE type = 'table' '''
    cursor.execute(sql)
    values = cursor.fetchall()
    tables = []
    for v in values:
        tables.append(v[0])
    if table_name not in tables:
        return False # 可以建表
    else:
        return True # 不能建表
def find_tb():
    cur.execute("select * from scores")
    # 提取查询到的数据
    return cur.fetchall()
def zcd():
    os.system('cls')
    print("学生分数管理系统")
    print("1.增加学生分数信息")
    print("2.查看全部学生分数")
    print("3.查询分数段内学生分数")
    print("4.退出")

if __name__ == '__main__':
    # 创建与数据库的连接
    conn = sqlite3.connect('stuents_scores.db')
    #创建一个游标 cursor
    cur = conn.cursor()
    # 如果没有表则执行建表的sql语句
    if (check("stuents_scores.db","scores") == False):
        sql_text_1 = '''CREATE TABLE scores
                (姓名 TEXT,
                    班级 TEXT,
                    性别 TEXT,
                    语文 NUMBER,
                    数学 NUMBER,
                    英语 NUMBER,
                    总分 NUMBER);'''
        # 执行sql语句
        cur.execute(sql_text_1)
    zcd()
    while True:
        op = int(input("请输入:"))
        if op == 1:
            S_name = input("请输入要添加的学生的姓名(如:张三):")
            S_class = input("请输入要添加的学生的班级(如:一班):")
            S_xb = input("请输入该学生性别:")
            S_Chinese = int(input("请输入该学生语文成绩(只输入一个数字,如:82):"))
            S_Maths = int(input("请输入该学生数学成绩(只输入一个数字,如:95):"))
            S_English = int(input("请输入该学生英语成绩(只输入一个数字,如:98):"))
            S_gj = S_Maths+S_Chinese+S_English # 总分
            data = [(S_name, S_class, S_xb, S_Chinese, S_Maths, S_English,S_gj)]
            cur.executemany('INSERT INTO scores VALUES (?,?,?,?,?,?,?)', data)
            conn.commit()
            # cur.close()
            # conn.close()
            print("成功!")
            os.system('pause')
            os.system('cls')
            zcd()
        elif op == 2:
            info_list = find_tb()
            print("全部学生信息(排名不分前后):")
            for i in range(len(info_list)):
                print("第"+str(i+1)+"个:")
                print("学生姓名:"+str(info_list[i][0]))
                print("学生班级:"+str(info_list[i][1]))
                print("学生性别:"+str(info_list[i][2]))
                print("学生语文成绩:"+str(info_list[i][3]))
                print("学生数学成绩:"+str(info_list[i][4]))
                print("学生英语成绩:"+str(info_list[i][5]))
                print("学生总成绩:"+str(info_list[i][6]))
                os.system('pause')
                os.system('cls')
                zcd()
        elif op == 3:
            info_list = find_tb()
            fen = int(input("你要要查询总成绩高于n分的学生, 请输入n:"))
            for i in range(len(info_list)):
                if info_list[i][6] >= fen:
                    print("查询结果:")
                    print("第"+str(i+1)+"个:")
                    print("学生总成绩:"+str(info_list[i][6]))
            os.system('pause')
            os.system('cls')
            zcd()
        elif op == 4:
            os.system('cls')
            break

【相关推荐:Python3视频教程

The above is the detailed content of An in-depth chat about the sqlite3 database in Python. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete