为避免忘记,待日后可查参考,今天把PYTHON访问POSTGRESQL数据库的方法,记录一下,
1)使用了PSYCOPG2访问驱动接口,需要下载这个驱动,然后SETUP安装即可,
2)本次程序主要测试了如何插入数据到数据库,如何查询,如何调用存储过程这三个方面
3)代码如下:
-
import sys
-
import psycopg2
-
import datetime
-
import time
-
-
if __name__=="__main__":
-
try:
-
print("today is: ",datetime.datetime.now())
-
print("today is:",datetime.date.today())
-
print("time is :",time.strftime("%H:%M:%S",time.localtime()))
-
-
conn=psycopg2.connect("host=localhost dbname=testdb user=postgres password=123 port=5432")
-
cur=conn.cursor()
-
-
cur.execute("select version()")
-
ver=cur.fetchone()
-
print("version %s:"%(ver))
-
-
-
vpo="PO-001"
-
vpart_no="A-001"
-
vpo_qty=100
-
vqty=20
-
vloc="LG01"
-
vtdate=datetime.date.today()
-
-
cur.execute("insert into pur_instk(po,part_no,po_qty,qty,loc,tdate) values(%s,%s,%s,%s,%s,%s)",
-
(vpo,vpart_no,vpo_qty,vqty,vloc,vtdate))
-
-
vpo="PO-002"
-
vpart_no="A-002"
-
vpo_qty=100
-
vqty=20
-
vloc="LG02"
-
vtdate=datetime.date.today()
-
-
cur.execute("insert into pur_instk(po,part_no,po_qty,qty,loc,tdate) values(%s,%s,%s,%s,%s,%s)",
-
(vpo,vpart_no,vpo_qty,vqty,vloc,vtdate))
-
-
vpo="PO-003"
-
vpart_no="A-003"
-
vpo_qty=100
-
vqty=20
-
vloc="LG03"
-
vtdate=datetime.date.today()
-
-
cur.execute("insert into pur_instk(po,part_no,po_qty,qty,loc,tdate) values(%s,%s,%s,%s,%s,%s)",
-
(vpo,vpart_no,vpo_qty,vqty,vloc,vtdate))
-
-
conn.commit()
-
-
cur.execute("select * from pur_instk")
-
rec=cur.fetchall()
-
print("record count is :%d"%(len(rec)))
-
-
for r in rec:
-
print(r[0],r[1],r[2],r[3],r[4],r[5])
-
-
cur.callproc("testz_sum",[10,20])
-
vsum=cur.fetchone()
-
print("call stored proc,result sum = %d"%(vsum))
-
-
cur.close()
-
conn.close()
-
-
except Exception as e:
-
conn.rollback()
-
print("occur a fatel error ,please check!")
-
print(e)
4)代码简述:
A:用POSTGRESQL在后台建立一个数据表,用PYTHON前端插入三条记录, commit提交,
然后再查询出来。
B:写一个testz_sum存储过程,二个参数,在里面做个简单处理,返回结果
5)运行结果:
today is: 2014-07-01 10:26:37.062500
today is: 2014-07-01
time is : 10:26:37
version PostgreSQL 9.2.2, compiled by Visual C++ build 1600, 32-bit:
record count is :3
PO-001 A-001 100.0000 20.0000 LG01 2014-07-01
PO-002 A-002 100.0000 20.0000 LG02 2014-07-01
PO-003 A-003 100.0000 20.0000 LG03 2014-07-01
call stored proc,result sum = 35
阅读(1491) | 评论(0) | 转发(0) |