PostgreSQL - Python 接口


安装

PostgreSQL 可以使用 psycopg2 模块与 Python 集成。sycopg2 是 Python 编程语言的 PostgreSQL 数据库适配器。psycopg2 的编写目标是非常小、速度快、稳定如磐石。您不需要单独安装此模块,因为默认情况下它是随 Python 版本 2.5.x 一起提供的。

如果您的计算机上没有安装它,那么您可以使用 yum 命令安装它,如下所示 -

$yum install python-psycopg2

要使用 psycopg2 模块,您必须首先创建一个代表数据库的 Connection 对象,然后您可以选择创建游标对象,它将帮助您执行所有 SQL 语句。

Python psycopg2 模块 API

以下是重要的 psycopg2 模块例程,它们可以满足您从 Python 程序使用 PostgreSQL 数据库的要求。如果您正在寻找更复杂的应用程序,那么您可以查看Python psycopg2模块的官方文档。

S. 编号 接口及说明
1

psycopg2.connect(数据库=“testdb”,用户=“postgres”,密码=“cohondob”,主机=“127.0.0.1”,端口=“5432”)

此 API 打开与 PostgreSQL 数据库的连接。如果数据库打开成功,则返回一个连接对象。

2

连接.cursor()

此例程创建一个游标,该游标将在您使用 Python 进行数据库编程的整个过程中使用。

3

光标.execute(sql [,可选参数])

该例程执行一条 SQL 语句。SQL 语句可以被参数化(即,用占位符代替 SQL 文字)。psycopg2 模块支持使用 %s 符号的占位符

例如:cursor.execute("插入人物值(%s,%s)",(who,age))

4

游标.executemany(sql, seq_of_parameters)

此例程针对序列 sql 中找到的所有参数序列或映射执行 SQL 命令。

5

光标.callproc(procname[, 参数])

该例程执行具有给定名称的存储数据库过程。参数序列必须为过程所需的每个参数包含一个条目。

6

游标行数

此只读属性返回上次执行 *() 修改、插入或删除的数据库行总数。

7

连接.commit()

该方法提交当前事务。如果不调用此方法,则自上次调用 commit() 以来所做的任何操作对于其他数据库连接都是不可见的。

8

连接.rollback()

此方法回滚自上次调用 commit() 以来对数据库的任何更改。

9

连接.close()

该方法关闭数据库连接。请注意,这不会自动调用 commit()。如果您只是关闭数据库连接而不先调用 commit(),您的更改将会丢失!

10

游标.fetchone()

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

11

光标.fetchmany([size=cursor.arraysize])

此例程获取查询结果的下一组行,并返回一个列表。当没有更多行可用时,将返回空列表。该方法尝试获取大小参数指示的尽可能多的行。

12

游标.fetchall()

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

连接到数据库

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

#!/usr/bin/python

import psycopg2

conn = psycopg2.connect(database="testdb", user = "postgres", password = "pass123", host = "127.0.0.1", port = "5432")

print "Opened database successfully"

在这里,您还可以提供数据库testdb作为名称,如果数据库成功打开,那么它将给出以下消息 -

Open database successfully

创建一个表

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

#!/usr/bin/python

import psycopg2

conn = psycopg2.connect(database = "testdb", user = "postgres", password = "pass123", host = "127.0.0.1", port = "5432")
print "Opened database successfully"

cur = conn.cursor()
cur.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.commit()
conn.close()

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

Opened database successfully
Table created successfully

插入操作

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

#!/usr/bin/python

import psycopg2

conn = psycopg2.connect(database = "testdb", user = "postgres", password = "pass123", host = "127.0.0.1", port = "5432")
print "Opened database successfully"

cur = conn.cursor()

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

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

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

cur.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 psycopg2

conn = psycopg2.connect(database = "testdb", user = "postgres", password = "pass123", host = "127.0.0.1", port = "5432")
print "Opened database successfully"

cur = conn.cursor()

cur.execute("SELECT id, name, address, salary  from COMPANY")
rows = cur.fetchall()
for row in rows:
   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 psycopg2

conn = psycopg2.connect(database = "testdb", user = "postgres", password = "pass123", host = "127.0.0.1", port = "5432")
print "Opened database successfully"

cur = conn.cursor()

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

cur.execute("SELECT id, name, address, salary  from COMPANY")
rows = cur.fetchall()
for row in rows:
   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 psycopg2

conn = psycopg2.connect(database = "testdb", user = "postgres", password = "pass123", host = "127.0.0.1", port = "5432")
print "Opened database successfully"

cur = conn.cursor()

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

cur.execute("SELECT id, name, address, salary  from COMPANY")
rows = cur.fetchall()
for row in rows:
   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