Sqlite3 instance of Python Standard Library

Source: Internet
Author: User
This article mainly introduces the sqlite3 instance of the Python standard library. This article describes how to create a database, insert data, query data, update and delete data operation instances, for more information, see Python's built-in lightweight relational database SQLite. This database uses the SQL language. As a back-end database, SQLite can be used with Python to build websites or create tools with data storage needs. SQLite is also widely used in other fields, such as HTML5 and mobile terminals. Sqlite3 in The Python Standard Library provides interfaces for this database.

I will create a simple relational database to classify and store books for a bookstore. The database contains two tables: category is used to record the category, and book is used to record the information of a book. A book belongs to a certain category. Therefore, the book has a foreign key pointing to the primary key id of the catogory table.

Create a database

First, create a database and tables in the database. After connecting to the database using connect (), I can locate the pointer cursor and execute the SQL command:

The code is as follows:


# By Vamei
Import sqlite3
# Test. db is a file in the working directory.
Conn = sqlite3.connect ("test. db ")
C = conn. cursor ()
# Create tables
C.exe cute (''' create table category
(Id int primary key, sort int, name text )''')
C.exe cute (''' create table book
(Id int primary key,
Sort int,
Name text,
Price real,
Category int,
Foreign key (category) REFERENCES category (id ))''')
# Save the changes
Conn. commit ()
# Close the connection with the database
Conn. close ()

The SQLite database is a file on a disk, as shown in test. db above. Therefore, the entire database can be conveniently moved or copied. Test. db does not exist at the beginning, so SQLite will automatically create a new file.

Using the execute () command, I executed two SQL commands to create two tables in the database. After creation, save and disconnect the database.

Insert data

The database and table are created above, and the abstract structure of the database is established. Insert data in the same database as follows:

The code is as follows:


# By Vamei
Import sqlite3
Conn = sqlite3.connect ("test. db ")
C = conn. cursor ()
Books = [(1, 1, 'Cook repository', 3.12, 1 ),
(2, 3, 'Python ino', 17.5, 2 ),
(3, 2, 'OS intro', 13.6, 2 ),
]
# Execute "INSERT"
C.exe cute ("insert into category VALUES (1, 1, 'kitchen ')")
# Using the placeholder
C.exe cute ("insert into category VALUES (?, ?, ?) ", [(2, 2, 'computer ')])
# Execute multiple commands
C.exe cute.pdf ('Insert INTO book VALUES (?, ?, ?, ?, ?) ', Books)
Conn. commit ()
Conn. close ()

You can also use execute () to insert data to execute the complete SQL statement. For parameters in SQL statements, use "? "As an alternative symbol, and the specific value is given in the following parameters. The format string of Python, such as "% s", cannot be used here because it is vulnerable to SQL injection attacks.

I can also use the executeplugin () method to execute multiple inserts and add multiple records. Each record is an element in the table.

Query

After a query statement is executed, Python returns a iterator containing multiple records obtained from the query. You can also use the fetchone () and fetchall () methods provided by sqlite3 to read records cyclically:

The code is as follows:


# By Vamei
Import sqlite3
Conn = sqlite3.connect ('test. db ')
C = conn. cursor ()
# Retrieve one record
C.exe cute ('select name FROM category order by sort ')
Print (c. fetchone ())
Print (c. fetchone ())
# Retrieve all records as a list
C.exe cute ('select * FROM book WHERE book. category = 1 ')
Print (c. fetchall ())
# Iterate through the records
For row in c.exe cute ('select name, price FROM book order by sort '):
Print (row)

Update and delete

You can update or delete a record:

The code is as follows:


# By Vamei
Conn = sqlite3.connect ("test. db ")
C = conn. cursor ()
C.exe cute ('update book SET price =? WHERE id =? ', (1000, 1 ))
C.exe cute ('delete FROM book WHERE id = 2 ')
Conn. commit ()
Conn. close ()

You can also directly delete the entire table:

The code is as follows:


C.exe cute ('drop TABLE book ')

If you delete test. db, the entire database is deleted.

Summary

Sqlite3 is just an SQLite interface. To use the SQLite database skillfully, you also need to learn more about relational databases.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.