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

Class to connect postgres with python in psycopg2

2015-08-24 22:33 801 查看
For we need to connect the postgres db in project very frequently, so write the follows class:

import psycopg2
#finish the work with task schedule
class dbwork:
def __init__(self,work_content,dbname='taskschedule',user='rl_dev',password='123456', host='10.0.39.46',port=5432):
self.dbname=dbname
self.user=user
self.password=password
self.host=host
self.port=port
self.work_content=work_content
def dowork(self):
conn=psycopg2.connect(database=self.dbname , user=self.user, password=self.password,host=self.host,port=self.port)
# Open a cursor to perform database operations
cur=conn.cursor()
# Execute a command: this creates a new table
sqlstr=self.work_content
#print 'sqlstr:'+sqlstr
if sqlstr.__contains__("update") or sqlstr.__contains__("UPDATE") or sqlstr.__contains__("delete") or sqlstr.__contains__("DELETE") or sqlstr.__contains__("insert") or sqlstr.__contains__("INSERT"):
cur.execute(sqlstr)
#if the sql action is a transaction, need to do commit
conn.commit()
cur.close()
conn.close()
else:
#if the sql action is not a transaction , return the result derectly
cur.execute(self.work_content)
result = cur.fetchall()
cur.close()
conn.close()

return result

#cur.execute("CREATE TABLE test (id serial PRIMARY KEY, num integer, data varchar);")
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: