用Python去PG中执行SQL并取出返回数据

概述

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()
  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值