PostgreSQL Python接口

PostgreSQL Python接口

安装

PostgreSQL可以使用psycopg2模块与Python集成。psycopg2是Python编程语言的PostgreSQL数据库适配器。psycopg2的目标是非常小、快速和稳定。您无需单独安装此模块,因为它默认与Python 2.5.x版本及以上版本一同安装。

如果您没有在计算机上安装它,则可以使用yum命令进行安装,如下所示:

$yum install python-psycopg2

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

Python psycopg2模块API

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

序号 API 和描述
1 psycopg2.connect(database=”testdb”, user=”postgres”, password=”cohondob”, host=”127.0.0.1″, port=”5432″) 该API用于打开连接到PostgreSQL数据库。如果数据库成功打开,则返回一个连接对象。
2 connection.cursor() 该函数用于创建一个 光标 ,它将在Python数据库编程的整个过程中使用。
3 cursor.execute(sql [, optional parameters]) 该函数用于执行一个SQL语句。SQL语句可以是参数化的(即,使用占位符代替SQL字面值)。psycopg2模块支持使用%s作为占位符。 例如:cursor.execute(“insert into people values (%s, %s)”, (who, age))
4 cursor.executemany(sql, seq_of_parameters) 这个方法执行一个SQL命令,并使用在序列sql中找到的所有参数序列或映射。
5 cursor.callproc(procname[, parameters]) 这个方法执行一个具有给定名称的存储过程。参数序列必须包含存储过程所期望的每个参数的一个条目。
6 cursor.rowcount 这个只读属性返回最后一次execute*()操作修改、插入或删除的数据库行的总数。
7 connection.commit() 这个方法提交当前事务。如果你不调用该方法,自从上次调用commit()以来所做的任何操作对其他数据库连接是不可见的。
8 connection.rollback() 此方法将回滚自上次提交(commit())以来对数据库所做的任何更改。
9 connection.close() 此方法关闭数据库连接。请注意,这不会自动调用提交(commit())。如果您在关闭数据库连接之前没有调用提交(commit()),您的更改将丢失!
10 cursor.fetchone() 此方法获取查询结果集的下一行,返回一个单个序列,或在没有更多数据可用时返回None。
11 cursor.fetchmany([size=cursor.arraysize]) 此方法获取查询结果的下一组行,返回一个列表。当没有更多行可用时,返回一个空列表。该方法尝试获取由size参数指示的尽可能多的行数。
12 cursor.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

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程