您的位置:首页 > 编程语言 > Python开发

Python基础--python操作sqlite

2016-03-30 20:32 316 查看
sqlite数据库大家都不会模式

十分的轻量级,今天就简单的说一说Python中如何使用sqlite。

在比较新的Python中就包含了sqlite,所以不需要单独下载。我们直接导入sqlite模块即可了:

先上一段代码吧:

import sqlite3

sqlite_file = 'my_first_db.db'    # 数据库名
table_name1 = 'my_table_1'        # 创建的表的名称
table_name2 = 'my_table_2'        # 创建的表的名称
new_field = 'my_1st_column'       # name of the column
field_type = 'INTEGER'            # column data type

# Connecting to the database file
conn = sqlite3.connect(sqlite_file)
c = conn.cursor() #获得连接的游标

# Creating a new SQLite table with 1 column
c.execute('CREATE TABLE {tn} ({nf} {ft})'\
.format(tn=table_name1, nf=new_field, ft=field_type))

# Creating a second table with 1 column and set it as PRIMARY KEY
# note that PRIMARY KEY column must consist of unique values!
c.execute('CREATE TABLE {tn} ({nf} {ft} PRIMARY KEY)'\
.format(tn=table_name2, nf=new_field, ft=field_type))

# Committing changes and closing the connection to the database file
conn.commit()
conn.close()


运行后,使用软件打开数据库,我们发现里面有两张表,my_table_1和my_table_2



接下来就开始:

conn = sqlite3.connect()

如果数据库不存在,则创建一个数据库

conn.cursor()

获得连接游标

这里看一下sqlite中可以使用的类型:

INTEGER: A signed integer up to 8 bytes depending on the magnitude of the value.
REAL: An 8-byte floating point value.
TEXT: A text string, typically UTF-8 encoded (depending on the database encoding).
BLOB: A blob of data (binary large object) for storing binary data.
NULL: A NULL value, represents missing data or an empty cell.


最后看一下API:

sqlite3.connect(database [,timeout ,other optional arguments])
This API opens a connection to the SQLite database file database. You can use ":memory:" to open a database connection to a database that resides in RAM instead of on disk. If database is opened successfully, it returns a connection object.

When a database is accessed by multiple connections, and one of the processes modifies the database, the SQLite database is locked until that transaction is committed. The timeout parameter specifies how long the connection should wait for the lock to go away until raising an exception. The default for the timeout parameter is 5.0 (five seconds).

If given database name does not exist then this call will create the database. You can specify filename with required path as well if you want to create database anywhere else except in current directory.

2   connection.cursor([cursorClass])
This routine creates a cursor which will be used throughout of your database programming with Python. This method accepts a single optional parameter cursorClass. If supplied, this must be a custom cursor class that extends sqlite3.Cursor.

3   cursor.execute(sql [, optional parameters])
This routine executes an SQL statement. The SQL statement may be parameterized (i. e. placeholders instead of SQL literals). The sqlite3 module supports two kinds of placeholders: question marks and named placeholders (named style).

For example:cursor.execute("insert into people values (?, ?)", (who, age))

4   connection.execute(sql [, optional parameters])
This routine is a shortcut of the above execute method provided by cursor object and it creates an intermediate cursor object by calling the cursor method, then calls the cursor's execute method with the parameters given.

5   cursor.executemany(sql, seq_of_parameters)
This routine executes an SQL command against all parameter sequences or mappings found in the sequence sql.

6   connection.executemany(sql[, parameters])
This routine is a shortcut that creates an intermediate cursor object by calling the cursor method, then calls the cursor.s executemany method with the parameters given.

7   cursor.executescript(sql_script)
This routine executes multiple SQL statements at once provided in the form of script. It issues a COMMIT statement first, then executes the SQL script it gets as a parameter. All the SQL statements should be separated by semi colon (;).

8   connection.executescript(sql_script)
This routine is a shortcut that creates an intermediate cursor object by calling the cursor method, then calls the cursor's executescript method with the parameters given.

9   connection.total_changes()
This routine returns the total number of database rows that have been modified, inserted, or deleted since the database connection was opened.

10  connection.commit()
This method commits the current transaction. If you don.t call this method, anything you did since the last call to commit() is not visible from other database connections.

11  connection.rollback()
This method rolls back any changes to the database since the last call to commit().

12  connection.close()
This method closes the database connection. Note that this does not automatically call commit(). If you just close your database connection without calling commit() first, your changes will be lost!

13  cursor.fetchone()
This method fetches the next row of a query result set, returning a single sequence, or None when no more data is available.

14  cursor.fetchmany([size=cursor.arraysize])
This routine fetches the next set of rows of a query result, returning a list. An empty list is returned when no more rows are available. The method tries to fetch as many rows as indicated by the size parameter.

15  cursor.fetchall()
This routine fetches all (remaining) rows of a query result, returning a list. An empty list is returned when no rows are available.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: