PostgreSQL连接Python

1、安装

PostgreSQL可以用Python psycopg2模块集成。 sycopg2是Python编程语言的PostgreSQL数据库的适配器。 其程序代码少,速度快,稳定。不需要单独安装这个模块,因为它默认情况下被运往随着Python版本在2.5.x一起的。如果不把它安装在机器上,然后可以使用yum命令安装它,如下所示

sudo aptitude install python-psycopg2


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

2、Python psycopg2 模块APIs

以下是psycopg2的重要的的模块例程可以满足Python程序与PostgreSQL数据库的工作。如果寻找一个更复杂的应用程序,那么可以看看Python psycopg2的模块的官方文档


S.N. API & 描述
1 psycopg2.connect(database="testdb", user="postgres", password="cohondob", host="127.0.0.1", port="5432") 

这个API打开一个连接到PostgreSQL数据库。如果成功打开数据库时,它返回一个连接对象。 www.yiibai.com

2 connection.cursor()

该程序创建一个光标将用于整个数据库使用Python编程。 yiibai.com

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

此例程执行SQL语句。可被参数化的SQL语句(即占位符,而不是SQL文字)。 psycopg2的模块支持占位符用%s标志 yiibai.com

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

4 curosr.executemany(sql, seq_of_parameters)

该程序执行SQL命令对所有参数序列或序列中的sql映射。 www.yiibai.com

5 curosr.callproc(procname[, parameters])

这个程序执行的存储数据库程序给定的名称。该程序预计为每一个参数,参数的顺序必须包含一个条目。

6 cursor.rowcount

这个只读属性,它返回数据库中的行的总数已修改,插入或删除最后 execute*().

7 connection.commit()

此方法提交当前事务。如果不调用这个方法,无论做了什么修改,自从上次调用commit()是不可见的,从其他的数据库连接。

8 connection.rollback()

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

9 connection.close()

此方法关闭数据库连接。请注意,这并不自动调用commit()。如果你只是关闭数据库连接而不调用commit()方法首先,那么所有更改将会丢失!www.yiibai.com

10 cursor.fetchone()

这种方法提取的查询结果集的下一行,返回一个序列,或者无当没有更多的数据是可用的。

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

这个例程中取出下一个组的查询结果的行数,返回一个列表。当没有找到记录,返回空列表。该方法试图获取尽可能多的行所显示的大小参数。

12 cursor.fetchall()

这个例程获取所有查询结果(剩余)行,返回一个列表。空行时则返回空列表。www.yiibai.com


Eg:
#!/usr/bin/python

import psycopg2
conn = psycopg2.connect(database="postgres",user="postgres")
print "Open database successfuly"

cur = conn.cursor()
cur.execute("drop table class")
cur.execute(''' create table class(
            id int primary key not null,
            name    text    not null,
            age     int     not null,
            address char(50) ); ''')
print "table create successfully"
conn.commit()

cur.execute("insert into class (id,name,age,address) values (1,'li',18,'china')")
cur.execute("insert into class (id,name,age,address) values (2,'liu',18,'china')")
cur.execute("insert into class (id,name,age,address) values (3,'ss',21,'china')")
conn.commit()
print "records create successfully"

cur.execute("select * from class")
rows = cur.fetchall()
for row in rows:
    print "id = ", row[0]
    print "name = ", row[1]
    print "age = ", row[2]
    print "address = ", row[3]
print "Operation done successfully"

cur.execute("update class set age = 25  where id=1")
conn.commit()
print "Total number of rows updated :", cur.rowcount
cur.execute("select id, name, age, address  from class")
rows = cur.fetchall()
for row in rows:
   print "id = ", row[0]
   print "name = ", row[1]
   print "age = ", row[2]
   :print "address = ", row[3], "\n"

print "Operation done successfully";

cur.execute("delete from class where id=2;")
conn.commit()
print "Total number of rows deleted :", cur.rowcount

cur.execute("select id, name, age, address  from class")
rows = cur.fetchall()
for row in rows:
   print "id = ", row[0]
   print "name = ", row[1]
   print "age = ", row[2]
   print "address = ", row[3], "\n"


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


结果:


sil4@debian:~$ python conn_postgresql.py
Open database successfuly
table create successfully
records create successfully
id =  1
name =  li
age =  18
address =  china                                             
id =  2
name =  liu
age =  18
address =  china                                             
id =  3
name =  ss
age =  21
address =  china                                             
Operation done successfully
Total number of rows updated : 1
id =  2
name =  liu
age =  18
address =  china                                              


id =  3
name =  ss
age =  21
address =  china                                              


id =  1
name =  li
age =  25
address =  china                                              


Operation done successfully
Total number of rows deleted : 1
id =  3
name =  ss
age =  21
address =  china                                              


id =  1
name =  li
age =  25
address =  china                                              


Operation done successfully



参考:http://www.yiibai.com/html/postgresql/2013/080998.html







  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值