Python连接PostgreSQL数据库实例代码方法

2018-09-1716:27:05数据库教程Comments5,319 views字数 4208阅读模式

PostgreSQL可以使用psycopg2模块与Python集成。sycopg2是用于Python编程语言的PostgreSQL数据库适配器。 psycopg2是非常小,快速,稳定的。 您不需要单独安装此模块,因为默认情况下它会随着Python 2.5.x版本一起发布。 如果还没有在您的机器上安装它,那么可以使用yum命令安装它,如下所示:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/sjk/4975.html

$yum install python-psycopg2
Shell

要使用psycopg2模块,必须首先创建一个表示数据库的Connection对象,然后可以选择创建可以帮助您执行所有SQL语句的游标对象。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/sjk/4975.html

连接到数据库

以下Python代码显示了如何连接到现有的数据库。 如果数据库不存在,那么它将自动创建,最后将返回一个数据库对象。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/sjk/4975.html

#!/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"
Python

在这里指定使用testdb作为数据库名称,如果数据库已成功打开连接,则会提供以下消息:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/sjk/4975.html

Open database successfully
Shell

创建表

以下Python程序将用于在先前创建的数据库(testdb)中创建一个表:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/sjk/4975.html

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

当执行上述程序时,它将在数据库testdb中创建COMPANY表,并显示以下消息:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/sjk/4975.html

Opened database successfully
Table created successfully
Shell

插入操作

以下Python程序显示了如何在上述示例中创建的COMPANY表中创建记录:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/sjk/4975.html

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

当执行上述程序时,它将在COMPANY表中创建/插入给定的记录,并显示以下两行:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/sjk/4975.html

Opened database successfully
Records created successfully
Shell

SELECT操作

以下Python程序显示了如何从上述示例中创建的COMPANY表中获取和显示记录:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/sjk/4975.html

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

执行上述程序时,会产生以下结果:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/sjk/4975.html

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
Shell

更新操作

以下Python代码显示了如何使用UPDATE语句来更新任何记录,然后从COMPANY表中获取并显示更新的记录:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/sjk/4975.html

文章源自菜鸟学院-https://www.cainiaoxueyuan.com/sjk/4975.html

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

执行上述程序时,会产生以下结果:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/sjk/4975.html

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
Shell

删除操作

以下Python代码显示了如何使用DELETE语句来删除记录,然后从COMPANY表中获取并显示剩余的记录:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/sjk/4975.html

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

执行上述程序时,会产生以下结果:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/sjk/4975.html

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
Shell
文章源自菜鸟学院-https://www.cainiaoxueyuan.com/sjk/4975.html
  • 本站内容整理自互联网,仅提供信息存储空间服务,以方便学习之用。如对文章、图片、字体等版权有疑问,请在下方留言,管理员看到后,将第一时间进行处理。
  • 转载请务必保留本文链接:https://www.cainiaoxueyuan.com/sjk/4975.html

Comment

匿名网友 填写信息

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定