search
HomeBackend DevelopmentPython TutorialAn in-depth chat about the sqlite3 database in Python

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. If there is any infringement, please contact admin@php.cn delete
The Main Purpose of Python: Flexibility and Ease of UseThe Main Purpose of Python: Flexibility and Ease of UseApr 17, 2025 am 12:14 AM

Python's flexibility is reflected in multi-paradigm support and dynamic type systems, while ease of use comes from a simple syntax and rich standard library. 1. Flexibility: Supports object-oriented, functional and procedural programming, and dynamic type systems improve development efficiency. 2. Ease of use: The grammar is close to natural language, the standard library covers a wide range of functions, and simplifies the development process.

Python: The Power of Versatile ProgrammingPython: The Power of Versatile ProgrammingApr 17, 2025 am 12:09 AM

Python is highly favored for its simplicity and power, suitable for all needs from beginners to advanced developers. Its versatility is reflected in: 1) Easy to learn and use, simple syntax; 2) Rich libraries and frameworks, such as NumPy, Pandas, etc.; 3) Cross-platform support, which can be run on a variety of operating systems; 4) Suitable for scripting and automation tasks to improve work efficiency.

Learning Python in 2 Hours a Day: A Practical GuideLearning Python in 2 Hours a Day: A Practical GuideApr 17, 2025 am 12:05 AM

Yes, learn Python in two hours a day. 1. Develop a reasonable study plan, 2. Select the right learning resources, 3. Consolidate the knowledge learned through practice. These steps can help you master Python in a short time.

Python vs. C  : Pros and Cons for DevelopersPython vs. C : Pros and Cons for DevelopersApr 17, 2025 am 12:04 AM

Python is suitable for rapid development and data processing, while C is suitable for high performance and underlying control. 1) Python is easy to use, with concise syntax, and is suitable for data science and web development. 2) C has high performance and accurate control, and is often used in gaming and system programming.

Python: Time Commitment and Learning PacePython: Time Commitment and Learning PaceApr 17, 2025 am 12:03 AM

The time required to learn Python varies from person to person, mainly influenced by previous programming experience, learning motivation, learning resources and methods, and learning rhythm. Set realistic learning goals and learn best through practical projects.

Python: Automation, Scripting, and Task ManagementPython: Automation, Scripting, and Task ManagementApr 16, 2025 am 12:14 AM

Python excels in automation, scripting, and task management. 1) Automation: File backup is realized through standard libraries such as os and shutil. 2) Script writing: Use the psutil library to monitor system resources. 3) Task management: Use the schedule library to schedule tasks. Python's ease of use and rich library support makes it the preferred tool in these areas.

Python and Time: Making the Most of Your Study TimePython and Time: Making the Most of Your Study TimeApr 14, 2025 am 12:02 AM

To maximize the efficiency of learning Python in a limited time, you can use Python's datetime, time, and schedule modules. 1. The datetime module is used to record and plan learning time. 2. The time module helps to set study and rest time. 3. The schedule module automatically arranges weekly learning tasks.

Python: Games, GUIs, and MorePython: Games, GUIs, and MoreApr 13, 2025 am 12:14 AM

Python excels in gaming and GUI development. 1) Game development uses Pygame, providing drawing, audio and other functions, which are suitable for creating 2D games. 2) GUI development can choose Tkinter or PyQt. Tkinter is simple and easy to use, PyQt has rich functions and is suitable for professional development.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools