How to use SQLite database in Python
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='table'
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='001'
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 ('宝玉',85,'计算机')" sql_insert_dy = "insert into mytb values ('黛玉',90,'计算机')" sql_insert_bc = "insert into mytb values ('宝钗',80,'数据库')" #(5)执行SQL语句,创建数据表mytb conn.execute(sql_create) #(6)依次插入3条记录,内容分别为:('宝玉',85,'计算机')、('黛玉',92,'计算机')、('宝钗',80,'数据库') 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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

The speed of mobile XML to PDF depends on the following factors: the complexity of XML structure. Mobile hardware configuration conversion method (library, algorithm) code quality optimization methods (select efficient libraries, optimize algorithms, cache data, and utilize multi-threading). Overall, there is no absolute answer and it needs to be optimized according to the specific situation.

It is impossible to complete XML to PDF conversion directly on your phone with a single application. It is necessary to use cloud services, which can be achieved through two steps: 1. Convert XML to PDF in the cloud, 2. Access or download the converted PDF file on the mobile phone.

There is no built-in sum function in C language, so it needs to be written by yourself. Sum can be achieved by traversing the array and accumulating elements: Loop version: Sum is calculated using for loop and array length. Pointer version: Use pointers to point to array elements, and efficient summing is achieved through self-increment pointers. Dynamically allocate array version: Dynamically allocate arrays and manage memory yourself, ensuring that allocated memory is freed to prevent memory leaks.

An application that converts XML directly to PDF cannot be found because they are two fundamentally different formats. XML is used to store data, while PDF is used to display documents. To complete the transformation, you can use programming languages and libraries such as Python and ReportLab to parse XML data and generate PDF documents.

XML can be converted to images by using an XSLT converter or image library. XSLT Converter: Use an XSLT processor and stylesheet to convert XML to images. Image Library: Use libraries such as PIL or ImageMagick to create images from XML data, such as drawing shapes and text.

To generate images through XML, you need to use graph libraries (such as Pillow and JFreeChart) as bridges to generate images based on metadata (size, color) in XML. The key to controlling the size of the image is to adjust the values of the <width> and <height> tags in XML. However, in practical applications, the complexity of XML structure, the fineness of graph drawing, the speed of image generation and memory consumption, and the selection of image formats all have an impact on the generated image size. Therefore, it is necessary to have a deep understanding of XML structure, proficient in the graphics library, and consider factors such as optimization algorithms and image format selection.

XML formatting tools can type code according to rules to improve readability and understanding. When selecting a tool, pay attention to customization capabilities, handling of special circumstances, performance and ease of use. Commonly used tool types include online tools, IDE plug-ins, and command-line tools.

There is no APP that can convert all XML files into PDFs because the XML structure is flexible and diverse. The core of XML to PDF is to convert the data structure into a page layout, which requires parsing XML and generating PDF. Common methods include parsing XML using Python libraries such as ElementTree and generating PDFs using ReportLab library. For complex XML, it may be necessary to use XSLT transformation structures. When optimizing performance, consider using multithreaded or multiprocesses and select the appropriate library.
