zoukankan      html  css  js  c++  java
  • Class to connect postgres with python in psycopg2

    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);")
  • 相关阅读:
    贪心:SPOJ Backup Files
    杂题 SPOJ MOBILE2
    杂题 UVAoj 10000 Longest Paths
    杂题 UVAoj 107 The Cat in the Hat
    DP(斜率优化):HDU 3507 Print Article
    搜索(DLX): POJ 3074 3076 Sudoku
    DLX模板
    PHP代码优化技巧大盘点
    盘点PHP编程常见失误
    PHP Socket 编程详解
  • 原文地址:https://www.cnblogs.com/allenz/p/4756140.html
Copyright © 2011-2022 走看看