Latest web development tutorials

SQLite - Python

installation

SQLite3 sqlite3 module can be used with Python integration. sqlite3 module written by Gerhard Haring. It provides a DB-API 2.0 specification described by PEP 249 is compatible with the SQL interface. You do not need to install the module separately, because Python 2.5.x or later default comes with the module.

In order to use sqlite3 module, you must first create a database connection object representation, and then you can choose to create a cursor object, which will help you perform all of the SQL statements.

Python sqlite3 module API

The following are important sqlite3 module program to meet your needs using SQLite database in Python programs. If you need more details, see the official documentation Python sqlite3 module.

序号API & 描述
1sqlite3.connect(database [,timeout ,other optional arguments])

该 API 打开一个到 SQLite 数据库文件 database 的链接。您可以使用 ":memory:" 来在 RAM 中打开一个到 database 的数据库连接,而不是在磁盘上打开。如果数据库成功打开,则返回一个连接对象。

当一个数据库被多个连接访问,且其中一个修改了数据库,此时 SQLite 数据库被锁定,直到事务提交。timeout 参数表示连接等待锁定的持续时间,直到发生异常断开连接。timeout 参数默认是 5.0(5 秒)。

如果给定的数据库名称 filename 不存在,则该调用将创建一个数据库。如果您不想在当前目录中创建数据库,那么您可以指定带有路径的文件名,这样您就能在任意地方创建数据库。

2connection.cursor([cursorClass])

该例程创建一个cursor,将在 Python 数据库编程中用到。该方法接受一个单一的可选的参数 cursorClass。如果提供了该参数,则它必须是一个扩展自 sqlite3.Cursor 的自定义的 cursor 类。

3cursor.execute(sql [, optional parameters])

该例程执行一个 SQL 语句。该 SQL 语句可以被参数化(即使用占位符代替 SQL 文本)。sqlite3 模块支持两种类型的占位符:问号和命名占位符(命名样式)。

例如:cursor.execute("insert into people values (?, ?)", (who, age))

4connection.execute(sql [, optional parameters])

该例程是上面执行的由光标(cursor)对象提供的方法的快捷方式,它通过调用光标(cursor)方法创建了一个中间的光标对象,然后通过给定的参数调用光标的 execute 方法。

5cursor.executemany(sql, seq_of_parameters)

该例程对 seq_of_parameters 中的所有参数或映射执行一个 SQL 命令。

6connection.executemany(sql[, parameters])

该例程是一个由调用光标(cursor)方法创建的中间的光标对象的快捷方式,然后通过给定的参数调用光标的 executemany 方法。

7cursor.executescript(sql_script)

该例程一旦接收到脚本,会执行多个 SQL 语句。它首先执行 COMMIT 语句,然后执行作为参数传入的 SQL 脚本。所有的 SQL 语句应该用分号(;)分隔。

8connection.executescript(sql_script)

该例程是一个由调用光标(cursor)方法创建的中间的光标对象的快捷方式,然后通过给定的参数调用光标的 executescript 方法。

9connection.total_changes()

该例程返回自数据库连接打开以来被修改、插入或删除的数据库总行数。

10connection.commit()

该方法提交当前的事务。如果您未调用该方法,那么自您上一次调用 commit() 以来所做的任何动作对其他数据库连接来说是不可见的。

11connection.rollback()

该方法回滚自上一次调用 commit() 以来对数据库所做的更改。

12connection.close()

该方法关闭数据库连接。请注意,这不会自动调用 commit()。如果您之前未调用 commit() 方法,就直接关闭数据库连接,您所做的所有更改将全部丢失!

13cursor.fetchone()

该方法获取查询结果集中的下一行,返回一个单一的序列,当没有更多可用的数据时,则返回 None。

14cursor.fetchmany([size=cursor.arraysize])

该方法获取查询结果集中的下一行组,返回一个列表。当没有更多的可用的行时,则返回一个空的列表。该方法尝试获取由 size 参数指定的尽可能多的行。

15cursor.fetchall()

该例程获取查询结果集中所有(剩余)的行,返回一个列表。当没有可用的行时,则返回一个空的列表。

Connect to the database

The following Python code shows how to connect to an existing database. If the database does not exist, it is created, and finally returns a database object.

#! / Usr / bin / python

import sqlite3

conn = sqlite3.connect ( 'test.db')

print "Opened database successfully";

Here, you can also copy the name of the database for a specificname: memory:, This will create a database in RAM.Now, let's run the above program, create our databasetest.db in the current directory.You can change the path as needed. Save the above code to sqlite.py file and press shown is performed as follows. If the database is successfully created, it will display the message shown below:

$ Chmod + x sqlite.py
$. / Sqlite.py
Open database successfully

Create a table

The following Python code will be used to create a table in the database previously created:

#! / Usr / bin / python

import sqlite3

conn = sqlite3.connect ( 'test.db')
print "Opened database successfully";

conn.execute ( '' 'CREATE TABLE COMPANY
       (ID INT PRIMARY KEY NOT NULL,
       NAME TEXT NOT NULL,
       AGE INT NOT NULL,
       ADDRESS CHAR (50),
       SALARY REAL); '' ')
print "Table created successfully";

conn.close ()

When the above procedure, it creates COMPANY table intest.db and displays the message shown below:

Opened database successfully
Table created successfully

INSERT operation

The following Python program shows how to create records in the COMPANY table created above:

#! / Usr / bin / python

import sqlite3

conn = sqlite3.connect ( 'test.db')
print "Opened database successfully";

conn.execute ( "INSERT INTO COMPANY (ID, NAME, AGE, ADDRESS, SALARY) \
      VALUES (1, 'Paul', 32, 'California', 20000.00) ");

conn.execute ( "INSERT INTO COMPANY (ID, NAME, AGE, ADDRESS, SALARY) \
      VALUES (2, 'Allen', 25, 'Texas', 15000.00) ");

conn.execute ( "INSERT INTO COMPANY (ID, NAME, AGE, ADDRESS, SALARY) \
      VALUES (3, 'Teddy', 23, 'Norway', 20000.00) ");

conn.execute ( "INSERT INTO COMPANY (ID, NAME, AGE, ADDRESS, SALARY) \
      VALUES (4, 'Mark', 25, 'Rich-Mond', 65000.00) ");

conn.commit ()
print "Records created successfully";
conn.close ()

The above program is executed, it will be created in the COMPANY table for a given record, and displays the following two lines:

Opened database successfully
Records created successfully

SELECT operations

The following Python program shows how to get from the COMPANY table created earlier and displays the record:

#! / Usr / bin / python

import sqlite3

conn = sqlite3.connect ( 'test.db')
print "Opened database successfully";

cursor = conn.execute ( "SELECT id, name, address, salary from COMPANY")
for row in cursor:
   print "ID =", row [0]
   print "NAME =", row [1]
   print "ADDRESS =", row [2]
   print "SALARY =", row [3], "\ n"

print "Operation done successfully";
conn.close ()

When the above program is executed, it will produce the following results:

Opened database successfully
ID = 1
NAME = Paul
ADDRESS = California
SALARY = 20000.0

ID = 2
NAME = Allen
ADDRESS = Texas
SALARY = 15000.0

ID = 3
NAME = Teddy
ADDRESS = Norway
SALARY = 20000.0

ID = 4
NAME = Mark
ADDRESS = Rich-Mond
SALARY = 65000.0

Operation done successfully

UPDATE operation

The following Python code shows how to use the UPDATE statement to update any records, then get from COMPANY table and display the updated record:

#! / Usr / bin / python

import sqlite3

conn = sqlite3.connect ( 'test.db')
print "Opened database successfully";

conn.execute ( "UPDATE COMPANY set SALARY = 25000.00 where ID = 1")
conn.commit
print "Total number of rows updated:", conn.total_changes

cursor = conn.execute ( "SELECT id, name, address, salary from COMPANY")
for row in cursor:
   print "ID =", row [0]
   print "NAME =", row [1]
   print "ADDRESS =", row [2]
   print "SALARY =", row [3], "\ n"

print "Operation done successfully";
conn.close ()

When the above program is executed, it will produce the following results:

Opened database successfully
Total number of rows updated: 1
ID = 1
NAME = Paul
ADDRESS = California
SALARY = 25000.0

ID = 2
NAME = Allen
ADDRESS = Texas
SALARY = 15000.0

ID = 3
NAME = Teddy
ADDRESS = Norway
SALARY = 20000.0

ID = 4
NAME = Mark
ADDRESS = Rich-Mond
SALARY = 65000.0

Operation done successfully

DELETE operation

The following Python code shows how to use the DELETE statement deletes any records, and then taken from the COMPANY table and displays the remaining recording:

#! / Usr / bin / python

import sqlite3

conn = sqlite3.connect ( 'test.db')
print "Opened database successfully";

conn.execute ( "DELETE from COMPANY where ID = 2;")
conn.commit
print "Total number of rows deleted:", conn.total_changes

cursor = conn.execute ( "SELECT id, name, address, salary from COMPANY")
for row in cursor:
   print "ID =", row [0]
   print "NAME =", row [1]
   print "ADDRESS =", row [2]
   print "SALARY =", row [3], "\ n"

print "Operation done successfully";
conn.close ()

When the above program is executed, it will produce the following results:

Opened database successfully
Total number of rows deleted: 1
ID = 1
NAME = Paul
ADDRESS = California
SALARY = 20000.0

ID = 3
NAME = Teddy
ADDRESS = Norway
SALARY = 20000.0

ID = 4
NAME = Mark
ADDRESS = Rich-Mond
SALARY = 65000.0

Operation done successfully