For we need to connect the postgres db in project very frequently, so write the follows class:
1 import psycopg2 2 #finish the work with task schedule 3 class dbwork: 4 def __init__(self,work_content,dbname='taskschedule',user='rl_dev',password='123456', host='10.0.39.46',port=5432): 5 self.dbname=dbname 6 self.user=user 7 self.password=password 8 self.host=host 9 self.port=port 10 self.work_content=work_content 11 def dowork(self): 12 conn=psycopg2.connect(database=self.dbname , user=self.user, password=self.password,host=self.host,port=self.port) 13 # Open a cursor to perform database operations 14 cur=conn.cursor() 15 # Execute a command: this creates a new table 16 sqlstr=self.work_content 17 #print 'sqlstr:'+sqlstr 18 if sqlstr.__contains__("update") or sqlstr.__contains__("UPDATE") or sqlstr.__contains__("delete") or sqlstr.__contains__("DELETE") or sqlstr.__contains__("insert") or sqlstr.__contains__("INSERT"): 19 cur.execute(sqlstr) 20 #if the sql action is a transaction, need to do commit 21 conn.commit() 22 cur.close() 23 conn.close() 24 else: 25 #if the sql action is not a transaction , return the result derectly 26 cur.execute(self.work_content) 27 result = cur.fetchall() 28 cur.close() 29 conn.close() 30 31 return result 32 33 #cur.execute("CREATE TABLE test (id serial PRIMARY KEY, num integer, data varchar);")