Use Python for SQLite database operations
1. Import
Python SQLite Database module
After the Python2.5, built-in SQLite3, has become a built-in module, which gives us to save the installation of Kung Fu, just import can ~
ImportSqlite3
2. Create/Open Database
When calling the Connect function, specify the name of the library, if the specified database exists, open the database directly, and 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 objects
The object that is returned when you open the database CX is a database connection object that can do the following:
- Rollback ()--Transaction rollback
- Close ()--Close a database connection
With respect to commit (), if the isolation_level isolation level defaults, then each operation on the database needs to use the command, you can also set isolation_level=none, This changes to autocommit mode.
4. Querying the database with cursors
We need to query the database using the Cursor object SQL statement to get the query object. Define a cursor by using the following method.
cu=cx.cursor ()
The cursor object has the following actions:
- Execute ()--Execute SQL statement
- executemany--executing multiple SQL statements
- Close ()--close cursor
- Fetchone ()--Takes a record from the result and points the cursor to the next record
- Fetchmany ()--take multiple records from the results
- Fetchall ()--Remove all records from the results
- Scroll ()--cursor scrolling
1. Build a table
Cu.execute ("CREATE TABLE catalog (ID integer primary key,pid integer,name varchar () unique,nickname text NULL)")
The above statement creates a table called catalog, which has a primary key ID, a PID, and a name,name that cannot be duplicated, and a nickname default is null.
2. Inserting Data
Be careful to avoid the following wording:
#never do this--insecurecan cause an injection attack
PID= $
Cu.execute ("... where pid = '%s '"%pid)The correct approach is to use the form t= (n,) if T is just a single value, because tuples are immutable.
forTinch[(0,Ten,'ABC','Yu'),(1, -,'CBA','Xu')]:
Cu.execute ("INSERT INTO catalog values (?,?,?,?)", T)Simply insert two rows of data, but you need to be reminded that it will not take effect until you submit it. We use the database connection object CX to commit commit and rollback rollback operations.
Cx.commit ()
3. Enquiry
Cu.execute ("SELECT * FROM Catalog")
To extract the queried data, use the FETCH function of the cursor, such as:
Cu.fetchall ()
[(0,Ten, U'ABC', U'Yu'), (1, -, U'CBA', U'Xu')]
If we use Cu.fetchone (), we first return the first item in the list and use it again, then we return to the second item and go down.
4. Modifications
Cu.execute ("Update Catalog Set name= ' boy ' where id = 0")
Cx.commit ()
Note that after you modify the data, submit
5. Delete
Cu.execute ("Delete from catalog where id = 1")
Cx.commit ()
6. Use Chinese
Please make sure your IDE or system default encoding is Utf-8, and add u before Chinese
x=u'Fish'
Cu.execute ("Update Catalog set name=? WHERE id = 0", X)
Cu.execute ("SELECT * FROM Catalog")
Cu.fetchall ()
[(0,Ten, U'\u9c7c', U'Yu'), (1, -, U'CBA', U'Xu')]
If you want to display a Chinese font, you need to print out each string in turn
In [ -]: forIteminchCu.fetchall ():
....: forelementinchItem:
....: Printelement,
....: Print
....:
0TenFish Yu
1 -CBA Xu
7.Row type
Row provides an index-based and case-sensitive approach to accessing columns with little memory overhead. The original text reads as follows:
sqlite3. Row provides both index-based and case-insensitive name-based access to columns with almost no memory overhead. I T would probably be better than your own custom dictionary-based approach or even a db_row based solution.
A detailed description of the Row object
-
-
class sqlite3. Row
-
A Row instance serves as a highly optimized row_factory for Connection objects. It tries to mimic a for a tuple in the most of its features.
It supports mapping access by column name and index, iteration, representation, equality testing and Len () .
If the Row objects has exactly the same columns and their members is 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's the first member of each tuple in cursor.description.
New in version 2.6.
The following examples illustrate
In [ -]: cx.row_factory=Sqlite3. Row
in [ to]: cu=Cx.cursor ()
in [ +]: Cu.execute ('SELECT * FROM Catalog')
out[ +]: <Sqlite3. Cursor Object at0x05666680>
in [ -]: R=Cu.fetchone ()
in [ the]: type (R)
out[ the]: <type'Sqlite3. Row'>
in [ *]: R
out[ *]: <Sqlite3. Row Object at0x05348980>
in [ $]: PrintR
(0,Ten, U'\u9c7c', U'Yu')
in [Panax Notoginseng]: Len (R)
out[Panax Notoginseng]: 4
in [ the]: r[2] #使用索引查询
out[ the]: U'\u9c7c'
in [ A]: R.keys ()
out[ A]: ['ID', 'PID', 'name', 'Nickname']
in [ the]: foreinchR:
....: PrintE,
....:
0TenFish Yu
Keyword query using columns
In [ +]: r['ID']
out[ +]: 0
in [ -]: r['name']
out[ -]: U'\u9c7c'
[Python] using Python for SQLite database operations