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);")
相关文章推荐
- Python实现读取目录所有文件的文件名并保存到txt文件代码
- A daemon process class in python
- ant编译脚本执行python
- python之mock
- 有关python中的id,is 等
- 将Python脚本打包成可执行文件
- 将Python脚本打包成可执行文件
- A python tool to static sim.log duration time
- 从错误中学python(5)——list的sort方法
- python-->django使用过程中碰到的异常总结
- python中用filter求素数
- python把str转换为int
- 在python中如何设置当前工作目录
- Python学习笔记:random模块
- python第三方库推荐 - dateutil
- Python 实现递归算法
- python 模块学习--Numpy
- python实现简单爬虫功能
- python常用模块
- Python中文件对象的访问模式