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);")
  • 相关阅读:
    css居中问题(转)
    Request.ServerVariables 各个参数的用法
    html5 画个球碰撞
    递归生成json
    AspNetPager分页结合存储过程的用法
    sql+aspnetpager+查询功能
    求1+2+……+n
    几种排序的比较 bitmapsort,qsort,set
    利用两个栈,反转其中一个栈的元素
    进程间通信(IPC, Inter Process Communication)读书笔记
  • 原文地址:https://www.cnblogs.com/allenz/p/4756140.html
Copyright © 2011-2022 走看看