search
HomeBackend DevelopmentPython TutorialHow to use SQLite database in Python

How to use SQLite database in Python

May 11, 2023 am 08:25 AM
pythonsqlite

SQL (Structured Query Language) is a general database query language. SQL has data definition, data operation and data control functions and can complete all the work of the database. When using SQL language, you only need to tell the computer "what to do" without telling it "how to do it".

There are two ways to use SQL language. One is to use it interactively in command mode directly; the other is to be embedded into main languages ​​such as C/C and Python.

Preliminary knowledge

Creation and connection of sqlite database

Creation and connection of sqlite database are divided into three steps:

(1) Import module

import sqlite3
#或者:
from sqlite3 import dbapi2       #导入sqlite3模块的dbapi2接口模块

(2) Use the connect method to create a database

connection=sqlite3.connect(filename) 
#filename为数据库文件名,如果该文件存在则打开该数据库,如果不存在则创建一个新的数据库文件。 
#该方法返回一个数据库连接对象

(3) Close the connection object

connection.close() 
#关闭连接,更新数据库文件

SQL statement to create a data table

The table is the storage relationship in the database A collection of data. A database usually contains multiple tables, such as student table, class table, teacher table, etc. Tables are related through foreign keys.

In SQL, the syntax structure of using the create statement to create a table is as follows:

create table 表名(字段1,…,字段n)

For example, create a mytb table:

create table if not exists mytb( xm char, cj real, kc text )

The table name is mytb; IF NOT EXISTS means if the database If the mytb data table does not exist, create the table; if the data table already exists, do nothing;

xm char, cj real, kc text means that the data table has 3 fields, xm ( name) is a string type, cj(grade) is a float type, and kc(course) is a text string.

SQLite3 supports data types:

null (value = null), integer (integer), real (floating point number), text (string text), blob (binary data block).

execute() method

In Python we can use the execute method to execute a SQL statement

conn.execute('create table if not exists mytb( xm char, cj real, kc text )')

conn is the connection object. The parameter in the execute() method is a SQL statement. The type is string

Insert record

(1) The SQL statement to insert record

The syntax format is as follows:

insert into 表名 [字段名] values [常量]

For example:

insert into Persons values ('Gates', 'Bill', 'Xuanwumen 10', 'Beijing')

(2) Use execute() to execute the SQL statement

cur.exceute(sql语句)

(3) Submit the transaction

conn.commit() #提交事务,将数据写入文件,保存到磁盘中。

Query the SQL statement

Query the expression that satisfies the condition from the "table" The "target column"

SELECT 目标列 FROM 表 [WHERE 条件表达式]

For example, query the names and ages of students under 20 years old:

select sname age from student where age<20

For example, query all records in the table:

select * from student

fetchall( )

Return multiple records (rows), if there is no result, return empty ()

sqlite_master table

Every SQLite database has a table called sqlite_master, The table is automatically created.

sqlite_master is a special table that stores meta-information of the database, such as table, index, view, and trigger. Related information can be queried through select.

select name,sql from sqlite_master where type=&#39;table&#39;

This statement is used to query the name of the data table in the database, and the SQL statement to create the table

Update records

SQL statement to update records:

UPDATE 表名 SET 列名=表达式… [WHERE 条件]

When the "condition" is established, change the value of a column to "expression". For example:

update student set cj=90 where xh="001"

You can change the score of student No. 001 to 90

Delete record

DROP TABLE and DELETE statements:

(1) Delete all records in the data table

DELETE FROM <表名>

For example, delete the student table

delete from student

(2) Delete records

DELETE FROM <表名> WHERE <条件>

For example, delete the record whose middle school number #Example exercises

Level 1: Create and connect database files

The task of this level: Create and connect the mytest.db database in the current directory.

Code analysis

delete from student where xh=&#39;001&#39;

Level 2: Create a data table

The task of this level: create or open a data table example.

Code analysis

DROP TABLE 表名

Level 3: Insert records

The task of this level: Create a sqlite3 database file mytest.db, and then create a data table mytb.db, go to Insert three rows of records into the table.

Code Analysis

drop table student

Level 4: Query Records

The task of this level: Design a program to query all records in the data table mytb in the existing database file myfile.db , and query the data table structure.

Code Analysis

def return_values():
#***********Begin**********#
    #(1)导入内置sqlite3模块
    import sqlite3
    #(2)创建conn连接对象(在当前路径下建立mytest.db数据库)
    conn = sqlite3.connect("mytest.db")
    #(3)关闭连接
    conn.close()
#***********End**********#

Level 5: Update and Delete Records

The task of this level: Update and delete records in the sqlite database

Code Analysis

#(1)导入sqlite3模块
import sqlite3
#(2)创建conn连接对象,建立mytest.db数据库
conn = sqlite3.connect("mytest.db")
#(3)定义sql语句,创建mytb数据表,表中有三个字段xm、cj、kc,其数据类型分别为char、real、text
sql_demo = "create table if not exists mytb( xm char , cj real , kc text )"
#(4)执行sql语句
conn.execute(sql_demo)
#(5)关闭连接
conn.close()

Level 6: Comprehensive operation of book database

The tasks of this level: create the database mybook.db in SQLite; create the data table mytb in the database; define in the table: isbn (text ), book title (text), price (real) and other fields, and insert records.

Code Analysis

#(1)导入sqlite3模块
import sqlite3
#(2)创建数据库文件mytest.db
conn = sqlite3.connect("mytest.db")
#(3)定义一个游标对象
cur = conn.cursor()
#(4)定义创建数据表SQL语句
sql_create = "create table if not exists mytb(xm char,cj real,kc text)"
sql_insert_by = "insert into mytb values (&#39;宝玉&#39;,85,&#39;计算机&#39;)"
sql_insert_dy = "insert into mytb values (&#39;黛玉&#39;,90,&#39;计算机&#39;)"
sql_insert_bc = "insert into mytb values (&#39;宝钗&#39;,80,&#39;数据库&#39;)"
#(5)执行SQL语句,创建数据表mytb
conn.execute(sql_create)
#(6)依次插入3条记录,内容分别为:(&#39;宝玉&#39;,85,&#39;计算机&#39;)、(&#39;黛玉&#39;,92,&#39;计算机&#39;)、(&#39;宝钗&#39;,80,&#39;数据库&#39;)
cur.execute(sql_insert_by)
cur.execute(sql_insert_dy)
cur.execute(sql_insert_bc)
#(7)提交事务
conn.commit()
#(8)关闭连接
cur.close()
conn.close()

The above is the detailed content of How to use SQLite database in Python. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:亿速云. If there is any infringement, please contact admin@php.cn delete
How does the choice between lists and arrays impact the overall performance of a Python application dealing with large datasets?How does the choice between lists and arrays impact the overall performance of a Python application dealing with large datasets?May 03, 2025 am 12:11 AM

ForhandlinglargedatasetsinPython,useNumPyarraysforbetterperformance.1)NumPyarraysarememory-efficientandfasterfornumericaloperations.2)Avoidunnecessarytypeconversions.3)Leveragevectorizationforreducedtimecomplexity.4)Managememoryusagewithefficientdata

Explain how memory is allocated for lists versus arrays in Python.Explain how memory is allocated for lists versus arrays in Python.May 03, 2025 am 12:10 AM

InPython,listsusedynamicmemoryallocationwithover-allocation,whileNumPyarraysallocatefixedmemory.1)Listsallocatemorememorythanneededinitially,resizingwhennecessary.2)NumPyarraysallocateexactmemoryforelements,offeringpredictableusagebutlessflexibility.

How do you specify the data type of elements in a Python array?How do you specify the data type of elements in a Python array?May 03, 2025 am 12:06 AM

InPython, YouCansSpectHedatatYPeyFeLeMeReModelerErnSpAnT.1) UsenPyNeRnRump.1) UsenPyNeRp.DLOATP.PLOATM64, Formor PrecisconTrolatatypes.

What is NumPy, and why is it important for numerical computing in Python?What is NumPy, and why is it important for numerical computing in Python?May 03, 2025 am 12:03 AM

NumPyisessentialfornumericalcomputinginPythonduetoitsspeed,memoryefficiency,andcomprehensivemathematicalfunctions.1)It'sfastbecauseitperformsoperationsinC.2)NumPyarraysaremorememory-efficientthanPythonlists.3)Itoffersawiderangeofmathematicaloperation

Discuss the concept of 'contiguous memory allocation' and its importance for arrays.Discuss the concept of 'contiguous memory allocation' and its importance for arrays.May 03, 2025 am 12:01 AM

Contiguousmemoryallocationiscrucialforarraysbecauseitallowsforefficientandfastelementaccess.1)Itenablesconstanttimeaccess,O(1),duetodirectaddresscalculation.2)Itimprovescacheefficiencybyallowingmultipleelementfetchespercacheline.3)Itsimplifiesmemorym

How do you slice a Python list?How do you slice a Python list?May 02, 2025 am 12:14 AM

SlicingaPythonlistisdoneusingthesyntaxlist[start:stop:step].Here'showitworks:1)Startistheindexofthefirstelementtoinclude.2)Stopistheindexofthefirstelementtoexclude.3)Stepistheincrementbetweenelements.It'susefulforextractingportionsoflistsandcanuseneg

What are some common operations that can be performed on NumPy arrays?What are some common operations that can be performed on NumPy arrays?May 02, 2025 am 12:09 AM

NumPyallowsforvariousoperationsonarrays:1)Basicarithmeticlikeaddition,subtraction,multiplication,anddivision;2)Advancedoperationssuchasmatrixmultiplication;3)Element-wiseoperationswithoutexplicitloops;4)Arrayindexingandslicingfordatamanipulation;5)Ag

How are arrays used in data analysis with Python?How are arrays used in data analysis with Python?May 02, 2025 am 12:09 AM

ArraysinPython,particularlythroughNumPyandPandas,areessentialfordataanalysis,offeringspeedandefficiency.1)NumPyarraysenableefficienthandlingoflargedatasetsandcomplexoperationslikemovingaverages.2)PandasextendsNumPy'scapabilitieswithDataFramesforstruc

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)