Detailed Python database (sqlite3) application _python

Source: Internet
Author: User
Tags commit sql injection sqlite sqlite database

Python brings a lightweight relational database SQLite. This database uses the SQL language. SQLite as a back-end database, you can build a Web site with Python or create tools that have data storage requirements. SQLite also has a wide range of applications in other areas, such as HTML5 and mobile terminals. The sqlite3 in the Python standard library provides an interface to the database.

I will create a simple relational database that stores the categories and prices of books for a bookstore. There are two tables in the database: category is used to record categories, and book is used to record information for a particular document. A book is assigned to a category, so it has a foreign key (foreign key) that points to the primary key ID of the Catogory table.

Creating a Database

I'll start by creating the database and the tables in the database. After connecting to the database using connect (), I can execute the SQL command by locating the pointer cursor:

# by Vamei
import sqlite3

# test.db are a file in the working directory.
conn = Sqlite3.connect ("test.db")

C = conn.cursor ()

# Create tables
c.execute (' Create TABLE category
   (ID int primary key, sort int, name text)
C.execute ("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, such as the test.db above, so the entire database can be easily moved or replicated. Test.db does not exist at first, 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 the creation is complete, save and disconnect the database.

Inserting data

The database and tables are created above to establish the abstract structure of the database. The following inserts data into the same database:

# by Vamei

import sqlite3

conn = Sqlite3.connect ("test.db")
c  = conn.cursor () Books

= [1, 1, ' Cook R Ecipe ', 3.12, 1,
      (2, 3, ' Python Intro ', 17.5, 2),
      (3, 2, ' OS Intro ', 13.6, 2),
      ]

# execute INSERT 
C.execute ("INSERT into category VALUES (1, 1, ' kitchen ')")

# using the placeholder
c.execute ("INSERT INTO Categ Ory values (?,?,?) ", [(2, 2, ' computer ')])

# Execute multiple commands
c.executemany (' INSERT into book VALUES (?,?,?,?,?), books)

conn.commit ()
conn.close ()

Inserting data can also use Execute () to execute a complete SQL statement. The arguments in the SQL statement, using the "?" As a substitution symbol, and gives a specific value in the following argument. You cannot use Python's format string, such as "%s", because this usage is susceptible to SQL injection attacks.

I can also use the Executemany () method to perform multiple inserts, adding multiple records. Each record is an element in the table, such as an element in the books table above.

Inquire

After executing the query, Python returns a loop containing multiple records obtained by the query. You can read loops by using the Fetchone () and Fetchall () methods provided by Sqlite3:

# by Vamei

import sqlite3

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

# retrieve
one record C.execute (' SELECT name from category order by sort ') print (
c.fetchone ())
print (C.fetchone ())

# Retrieve All records as a list
c.execute (' SELECT * to book WHERE Book.category=1 ')
print (C.fetchall ())

# iterate T Hrough the records
for row in C.execute (' SELECT name, price ' order by sort '):
  print (ROW)

Update and delete

You can update a record, or delete a record:

# by Vamei

conn = Sqlite3.connect ("test.db")
C = conn.cursor ()

c.execute (' UPDATE book SET price=? WHERE id=? ', (1000, 1))
C.execute (' DELETE from book WHERE id=2 ')

conn.commit () conn.close ()

You can also delete the entire table directly:

C.execute (' DROP TABLE book ')

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

Summarize

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

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

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.