您的位置:首页 > 编程语言 > Python开发

python访问postgresql

2011-04-11 16:12 323 查看
2011-04-11import pg

#!/usr/bin/python
# -*- coding: utf-8 -*
import sys
import logging

LOG_FILENAME = './log.txt'
logging.basicConfig(filename=LOG_FILENAME,level=logging.DEBUG,filemode='a')

#-1:exception,0:normal
class ConnDB():
def __init__(self):
self.connobj = None

#获取Conn对象
def getConn(self):
'''
This function opens a connection to a specified database on a given PostgreSQL server
'''
code = 0
try:
self.connobj=pg.connect(dbname="mydb",host="localhost",port=5432,user="xx",/
passwd="xx")
except TypeError,e:
code = -1
msg = "ConnDB::getConn:bad argument type, or too many arguments"
logging.debug(msg)
except SyntaxError,e:
code = -1
msg = "ConnDB::getConn:duplicate argument definition"
logging.debug(msg)
except pg.InternalError,e:
code = -1
msg = "ConnDB::getConn:some error occurred during pg connection definition"
logging.debug(msg)

return (code,self.connobj)

if __name__ == "__main__":

connobj = ConnDB()

#获取连接
code,conn = connobj.getConn()
if code == -1:
sys.exit(code)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: