14 Python standard library databases (sqlite3)

Author: Vamei Source: http: //www.cnblogs.com/vamei welcome to reprint, please keep this statement. Thank you!

 

Python comes with a lightweight relational database SQLite. This database using SQL language. SQLite as the backend database, it can be used with Python construction site, or making tool data storage needs. SQLite also have wide application in other areas, such as HTML5 and mobile terminal. Sqlite3 Python standard library provides an interface to the database.

I will create a simple relational database for storing a bookstore classification and price of the book. The database contains two tables: category classification for the record, book used to record information about a book. A classification attributable to a particular book, book thus has a foreign key (foreign key), the primary key of the table id catogory.

          

 

Create a database

I first of all to create the database and tables in the database. After using the connect () connect to the database, I'll be able to execute SQL commands by positioning the pointer cursor:

# By Vamei
import sqlite3

# test.db is 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()

SQLite database file on a disk, as in the above test.db, so that the entire database can be easily moved or copied. test.db beginning does not exist, SQLite will automatically create a new file.

Using the execute () command, I carried out two SQL commands to create two tables in the database. Once created, saved and disconnect from the database.

 

Insert data

Creating the database and table above, we established the abstract structure of the database. Will insert data in the same database:

# By Vamei
import sqlite3

conn = sqlite3.connect("test.db")
c    = conn.cursor()

books = [(1, 1, 'Cook Recipe', 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 category VALUES (?, ?, ?)", [(2, 2, 'computer')])

# execute multiple commands
c.executemany('INSERT INTO book VALUES (?, ?, ?, ?, ?)', books)

conn.commit()
conn.close()

Data can also be inserted using the execute () to perform a complete SQL statement. SQL statement parameters using the "?" As a substitute, and specific values ​​are given in subsequent parameter. Here Python format string can not be used, such as "% s", because this usage vulnerable to SQL injection attacks.

I can also perform multiple insertion executemany () method, add multiple records. Each record in the table is an element, such as the above books table of elements.

 

Inquire

After the execution of the query, Python returns a circulator, contains multiple records check obtained. You read cycle, can also be used fetchone sqlite3 provided () and fetchall () method reads the record:

# 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 * FROM book WHERE book.category=1')
print(c.fetchall())

# iterate through the records
for row in c.execute('SELECT name, price FROM book ORDER BY sort'):
    print(row)

 

Update and delete

You can update a record, or delete records:

# 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 an entire table directly:

c.execute('DROP TABLE book')

If you delete test.db, then the entire database will be deleted.

 

to sum up

sqlite3 just a SQLite interface. Skilled want to use SQLite database, also you need to learn more knowledge of relational databases.

Guess you like

Origin www.cnblogs.com/z3286586/p/11332450.html