Python - 数据库和 SQL


Python 编程语言具有强大的数据库编程功能。Python支持各种数据库,如SQLite、MySQL、Oracle、Sybase、PostgreSQL等。Python还支持数据定义语言(DDL)、数据操作语言(DML)和数据查询语句。数据库接口的 Python 标准是 Python DB-API。大多数 Python 数据库接口都遵循此标准。

以下是可用的 Python 数据库接口的列表:Python 数据库接口和 API。您必须为需要访问的每个数据库下载单独的 DB API 模块。

在本章中,我们将看到在Python编程语言中使用SQLite数据库。它是通过使用 python 的内置 sqlite3 模块来完成的。您应该首先创建一个代表数据库的连接对象,然后创建一些游标对象来执行 SQL 语句。

连接到数据库

以下 Python 代码展示了如何连接到现有数据库。如果数据库不存在,则会创建数据库,最后返回一个数据库对象。

#!/usr/bin/python

import sqlite3

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

print "Opened database successfully";

在这里,您还可以提供数据库名称作为特殊名称:内存:以在 RAM 中创建数据库。现在,让我们运行上面的程序在当前目录中创建数据库test.db。您可以根据您的要求更改路径。将上述代码保存在 sqlite.py 文件中并执行,如下所示。如果数据库创建成功,则会显示以下消息。

$chmod +x sqlite.py
$./sqlite.py
Open database successfully

创建一个表

以下 Python 程序将用于在之前创建的数据库中创建一个表。

#!/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()

当执行上述程序时,它将在test.db中创建 COMPANY 表,并显示以下消息 -

Opened database successfully
Table created successfully

插入操作

以下 Python 程序显示了如何在上例中创建的 COMPANY 表中创建记录。

#!/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()

当执行上述程序时,它将在 COMPANY 表中创建给定的记录,并显示以下两行 -

Opened database successfully
Records created successfully

选择操作

以下 Python 程序展示了如何从上例中创建的 COMPANY 表中获取并显示记录。

#!/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()

当执行上述程序时,将产生以下结果。

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

更新操作

以下 Python 代码演示了如何使用 UPDATE 语句更新任何记录,然后从 COMPANY 表中获取并显示更新的记录。

#!/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()

当执行上述程序时,将产生以下结果。

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

删除操作

以下 Python 代码演示了如何使用 DELETE 语句删除任意记录,然后从 COMPANY 表中获取并显示剩余记录。

#!/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()

当执行上述程序时,将产生以下结果。

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