概述
Python程序提供特定的模块来连接postgresql数据库,是psycopg2模块,使用该模块连接到数据库可以对其进行一些数据库操作,是自动运维pg的很好方式
安装psycopg模块
有些Python默认没有安装此模块,所以需要安装:
yum安装
有yum源可直接安装
yum install python-psycopg
或者手动安装模块包
https://pypi.org/
网址,搜索模块名,下载.tar.gz的源码
上传到机器上解压,在解压目录上执行
Python step.py build
Python step.py install
用pip安装
Python有自带的类似yum的安装模块的工具,如有安装,可直接使用
pip install psycopg2
使用
测试连接
用Python的命令端测试下取数据
>>> import psycopg2 :导入模块
>>>
>>> con = psycopg2.connect(database="postgres",user="postgres",password="postgres",host="192.168.56.17",port="5432") :配置连接信息
>>> con
<connection object at 0x13848b0; dsn: 'dbname=postgres user=postgres password=xxxxxxxx host=192.168.56.17 port=5432', closed: 0> 查看连接状态
>>>
配置连接完成之后,可执行SQL获取返回结果
>>>
>>> cur = con.cursor() :使用cursor()方法获取操作游标
cursor = db.cursor()
>>>
>>> cur.execute("select * from test") :使用execute方法执行SQL语句
>>>
>>> rows = cur.fetchall() :使用 fetchall() 方法获取全部数据
>>>
>>> print rows
[(1, 'das'), (1, 'das'), (1, 'das'), (1, 'das'), (1, 'das'), (1, 'das'), (1, 'das'), (1, 'das'), (1, 'das'), (1, 'das'), (1, 'das'), (1, 'das'), (1, 'das'), (1, 'das'), (1, 'das'), (1, 'das'), (1, 'das'), (1, 'das'), (1, 'das'), (1, 'das'), (1, 'das'), (1, 'das'), (1, 'das'), (1, 'das'), (1, 'das')]
>>>
我常用的连接类
若经常使用到取PG的数据,可以先定义好连接的类,方便后续使用:
class PGINFO:
def __init__(self,host, user, pwd, db, port):
self.host = host
self.user = user
self.pwd = pwd
self.db = db
self.port = port
def __GetConnect(self):
"""
得到连接信息
返回: conn.cursor()
"""
if not self.db:
raise(NameError, "没有设置数据库信息")
self.conn = psycopg2.connect(database=self.db, user=self.user, password=self.pwd, host=self.host, port=self.port)
cur = self.conn.cursor()
if not cur:
raise (NameError, "连接数据库失败")
else:
return cur
def ExecQuery(self, sql):
"""
执行查询语句
"""
if sql == 'close':
self.conn.close()
else:
cur = self.__GetConnect()
cur.execute(sql)
#resList = cur.fetchall()
return cur
使用的时候,给定相关的数据库连接信息变量
pg = PGINFO(host=host_PG8, user=user_PG8, pwd=pwd_PG8, db=db_PG8, port=port_PG8)
利用返回游标取数据
cur = pg.ExecQuery(found_sql)
a = cur.fetchone()