A brief introduction
SQLite database is a very small embedded open source database software, which means there is no independent maintenance process, and all maintenance comes from the program itself. It is a relational database management system that complies with ACID. Its design target is embedded, and it has been used in many embedded products. It occupies very low resources. In embedded devices, it may only require a few One hundred K of memory is enough. It can support mainstream operating systems such as Windows/Linux/Unix, and can be combined with many programming languages, such as Tcl, C#, PHP, Java, etc., as well as ODBC interfaces. It is also compared to the two open source worlds of Mysql and PostgreSQL. In terms of famous database management systems, its processing speed is faster than them all. The first Alpha version of SQLite was born in May 2000. It has been 10 years now, and SQLite has also ushered in a version. SQLite 3 has been released.
Installation and use
1. Import the Python SQLITE database module
After Python2.5, SQLite3 is built-in and becomes a built-in module. This saves us the installation effort and just imports it. ~
import sqlite3
2. Create/open database
When calling the connect function, specify the library name. If the specified database exists, open the database directly. If it does not exist, create a new one and open it.
cx = sqlite3.connect("E:/test.db")
You can also create a database in memory.
con = sqlite3.connect(":memory:")
3. Database connection object
The object cx returned when opening the database is a database connection object, which can have the following operations:
commit()- -Transaction submission
rollback()--Transaction rollback
close()--Close a database connection
cursor()--Create a cursor
About commit(), if the isolation_level isolation level is default, then every time This command is required for database operations. You can also set isolation_level=None to change to automatic submission mode.
4. Use cursor to query the database
We need to use the cursor object SQL statement to query the database and obtain the query object. Define a cursor in the following ways.
cu=cx.cursor()
The cursor object has the following operations:
execute()--execute sql statement
executemany--execute multiple sql statements
close()--close the cursor
fetchone()--fetch one record from the result and point the cursor to the next record
fetchmany()--fetch multiple records from the result
fetchall()--fetch all records from the result
scroll ()--Cursor scrolling
1. Create table
cu.execute("create table catalog (id integer primary key,pid integer,name varchar(10) UNIQUE,nickname text NULL)")
The above statement A table called catalog is created, which has a primary key id, a pid, and a name. The name cannot be repeated, and a nickname defaults to NULL.
2. Insert data
Please be careful to avoid the following writing:
# Never do this -- insecure will lead to injection attacks pid=200c.execute("... where pid = '%s'" % pid)
The correct approach is as follows. If t is just a single value, it should also be in the form of t=(n,), because the tuple is immutable.
for t in[(0,10,'abc','Yu'),(1,20,'cba','Xu')]: cx.execute("insert into catalog values (?,?,? ,?)", t)
Simply insert two rows of data, but you need to be reminded that it will only take effect after it is submitted. We use the database connection object cx to perform commit and rollback operations.
cx. commit()
3. Query
cu.execute("select * from catalog")
To extract the queried data, use the fetch function of the cursor, such as:
In [10]: cu .fetchall() Out[10]: [(0, 10, u'abc', u'Yu'), (1, 20, u'cba', u'Xu')]
If we use cu.fetchone (), first returns the first item in the list, and if used again, returns the second item, and so on.
4. Modify
In [12]: cu.execute("update catalog set name=' Boy' where id = 0") In [13]: cx.commit()
Note, submit after modifying the data
5. Delete
cu.execute("delete from catalog where id = 1") cx .commit()
6. To use Chinese
please make sure your IDE or system default encoding is utf-8, and add u
before Chinesex=u'鱼' cu.execute("update catalog set name=? where id = 0",x) cu.execute("select * from catalog") cu.fetchall() [(0, 10, u' u9c7c', u'Yu'), (1, 20, u'cba', u'Xu')]
If you want to display Chinese fonts, you need to print out each string in turn
In [26 ]: for item in cu.fetchall(): ....: for element in item: ....: print element, ....: print ....: 0 10 鱼 Yu 1 20 cba Xu
7.Row type
Row provides index-based and name-based case-sensitive access to columns with almost no memory overhead. The original text is as follows:
sqlite3.Row provides both index-based and case-insensitive name-based access to columns with almost no memory overhead. It will probably be better than your own custom dictionary-based approach or even a db_row based solution .
Row object detailed introduction
class sqlite3.Row
A Row instance serves as a highly optimized row_factory for Connection objects. It tries to mimic a tuple in most of its features.
It supports mapping access by column name and index, iteration, representation, equality testing and len().
If two Row objects have exactly the same columns and their members are equal, they compare equal.
Changed in version 2.6: Added iteration and equality (hashability ).
keys()
This method returns a tuple of column names. Immediately after a query, it is the first member of each tuple in Cursor.description.
New in version 2.6.