Python Basic Tutorial Summary 15--7 Custom Bulletin Board

Source: Internet
Author: User
Tags sqlite database python sqlite

1. Python for SQLite database operation

A simple introduction

SQLite database is a very small embedded open source database software, that is, there is no independent maintenance process, all the maintenance is from the program itself. It is a relational database management system that adheres to acid, it is designed to be embedded, and has been used in many embedded products, it occupies very low resources, in the embedded device, may only need hundreds of K of memory is enough. It can support Windows/linux/unix and so on mainstream operating system, and can be combined with many programming languages, such as TCL, C #, PHP, Java, and ODBC interface, also compared to MySQL, PostgreSQL, the two open source world-renowned database management system, is processing faster than they do. The first alpha version of SQLite was born in May 2000. So far there have been 10 years, SQLite also ushered in a version of SQLite 3 has been released.

Installation and use

1). Import the 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 ~

Import Sqlite3

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") can also create databases in memory. con = Sqlite3.connect (": Memory:")

3). Database Connection Object

The object that is returned when you open the database CX is a database connection object that can do the following:

    1. Commit ()--Transaction commit
    2. Rollback ()--Transaction rollback
    3. Close ()--Close a database connection
    4. Cursor ()--Create a cursor

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 using 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.

The Cu=cx.cursor () Cursor object has the following actions:
    1. Execute ()--Execute SQL statement
    2. executemany--executing multiple SQL statements
    3. Close ()--close cursor
    4. Fetchone ()--Takes a record from the result and points the cursor to the next record
    5. Fetchmany ()--take multiple records from the results
    6. Fetchall ()--Remove all records from the results
    7. Scroll ()--cursor scrolling

Build table

Cu.execute ("CREATE TABLE catalog (ID integer primary key,pid integer,name varchar (ten) 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.

Inserting Data

Be careful to avoid the following wording:

# never do this--insecure will cause an injection attack

pid=200
C.execute ("... where pid = '%s '"% pid) the correct approach is as follows, if T is just a single value, also in the form of t= (n,), because tuples are immutable.
For T in[(0,10, ' abc ', ' Yu '), (1,20, ' CBA ', ' Xu ')]:
Cx.execute (INSERT into catalog values (?,?,?,?), T) simply inserts two rows of data, but you need to be reminded that only after you have submitted it, To take effect. We use the database connection object CX to commit commit and rollback rollback operations.
Cx.commit ()

Inquire

Cu.execute ("SELECT * from Catalog")

To extract the queried data, use the FETCH function of the cursor, such as:

In [ten]: Cu.fetchall ()
OUT[10]: [(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.

Modify

In [Page]: Cu.execute ("Update Catalog set name= ' boy ' where id = 0")
In []: Cx.commit ()

Note that after you modify the data, submit

Delete

Cu.execute ("Delete from catalog where id = 1")
Cx.commit ()

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 [+]: for item in Cu.fetchall ():
....: for element in item:
.....: Print Element,
.....: Print
....:
0 10 Fish Yu
1 CBA Xu

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. It'll 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 [+]: c = cx.cursor ()

in [+]: C.execute (' select * from Catalog ')
OUT[32]: <sqlite3. Cursor Object at 0x05666680>

In [all]: R = C.fetchone ()

in [+]: type (R)
OUT[34]: <type ' sqlite3. Row ' >

in [+]: R
OUT[35]: <sqlite3. Row Object at 0x05348980>

In [approx]: print R
(0, ten, U ' \u9c7c ', U ' Yu ')

In [PNS]: Len (R)
OUT[37]: 4

In [all]: r[2] #使用索引查询
OUT[39]: U ' \u9c7c '

in [+]: R.keys ()
OUT[41]: [' id ', ' pid ', ' Name ', ' nickname ']

In [all]: for E in R:
...: Print E,
....:
0 10 Fish Yu

Keyword query using columns

In []: r[' id ']
OUT[43]: 0

In []: r[' name ']
OUT[44]: U ' \u9c7c '

Python Basic Tutorial Summary 15--7 Custom Bulletin Board

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.