一、安装PostgreSQL模块

yum install  postgresql-devel

pip3 install psycopg2

注意;安装时遇到./psycopg/psycopg.h:35:22: fatal error: libpq-fe.h: No such file or directory,如下图,

则执行该命令安装相关依赖:yum install postgresql-devel

二、数据库连接接口

由于Python统一了数据库连接的接口,所以psycopg2和 MySQLdb 在使用方式上是类似的:

pymysql.Connect()参数说明
host(str): MySQL服务器地址
port(int): MySQL服务器端口号
user(str): 用户名
password(str): 密码
database(str): 数据库名称 connection对象支持的方法
cursor() 使用该连接创建并返回游标
commit() 提交当前事务
rollback() 回滚当前事务
close() 关闭连接 cursor对象支持的方法
execute(op) 执行一个数据库的查询命令
fetchone() 取得结果集的下一行
fetchmany(size) 获取结果集的下几行
fetchall() 获取结果集中的所有行
rowcount() 返回数据条数或影响行数
close() 关闭游标对象

三、范例

MySql脚本

-- ----------------------------
-- Table structure for account
-- ----------------------------
DROP TABLE IF EXISTS `account`;
CREATE TABLE `account` (
`acctid` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
`name` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`money` decimal(50, 0) NULL DEFAULT NULL
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic; -- ----------------------------
-- Records of account
-- ----------------------------
INSERT INTO `account` VALUES ('', '张三', 50);
INSERT INTO `account` VALUES ('', '李四', 150);

Python程序

#   coding:utf8
import sys
import psycopg2 #PostgreSQL
class TransferMoney(object):
def __init__(self, conn):
self.conn = conn def check_acct_available(self, acctid):
cursor = self.conn.cursor()
try:
sql = "select * from account where acctid='%s'" % acctid
print("check_acct_available:" + sql)
cursor.execute(sql)
rs = cursor.fetchall()
if len(rs) != 1:
raise Exception("帐号%s不存在" % acctid)
finally:
cursor.close() def has_enough_money(self, acctid, money):
cursor = self.conn.cursor()
try:
sql = "select * from account where acctid='%s' and money>%s" % (
acctid, money)
print("has_enough_money:" + sql)
cursor.execute(sql)
rs = cursor.fetchall()
if len(rs) != 1:
raise Exception("帐号%s没有足够的金额" % acctid)
finally:
cursor.close() def reduce_money(self, acctid, money):
cursor = self.conn.cursor()
try:
sql = "update account set money=money-%s where acctid='%s' " % (
money, acctid)
print("reduce_money:" + sql)
cursor.execute(sql)
if cursor.rowcount != 1:
raise Exception("帐号%s减款失败" % acctid)
finally:
cursor.close() def add_money(self, acctid, money):
cursor = self.conn.cursor()
try:
sql = "update account set money=money+%s where acctid='%s' " % (
money, acctid)
print("add_money:" + sql)
cursor.execute(sql)
if cursor.rowcount != 1:
raise Exception("帐号%s加款失败" % acctid)
finally:
cursor.close() def transfer(self, source_acctid, target_acctid, money):
try:
self.check_acct_available(source_acctid)
self.check_acct_available(target_acctid)
self.has_enough_money(source_acctid, money)
self.reduce_money(source_acctid, money)
self.add_money(target_acctid, money)
self.conn.commit()
except Exception as e:
self.conn.rollback()
print("transfer出现异常:" + str(e))
raise e def main():
source_acctid = sys.argv[1]
print("转出帐号=" + source_acctid)
target_acctid = sys.argv[2]
print("转入帐号=" + target_acctid)
money = sys.argv[3]
print("金额=" + money) # 连接数据库 MySql
#conn = pymysql.Connect(
# host='localhost',
# port=3306,
# user='root',
# passwd='root',
# db='OtkDb',
# charset='utf8')     # 连接数据库PostgreSQL
    conn = psycopg2.connect(
      host='localhost',
      port=5432,
      user='postgres',
      password='postgres',
      database='OtkDb') tr_money = TransferMoney(conn) try:
tr_money.transfer(source_acctid, target_acctid, money)
except Exception as e:
print("main出现异常:" + str(e))
finally:
conn.close() if __name__ == '__main__':
main()

四、运行效果

PS H:\web\Python> & python h:\web\Python\01.MySql\db.py 1 2 50
转出帐号=1
转入帐号=2
金额=50
check_acct_available:select * from account where acctid=''
check_acct_available:select * from account where acctid=''
has_enough_money:select * from account where acctid='' and money>50
reduce_money:update account set money=money-50 where acctid=''
add_money:update account set money=money+50 where acctid='' PS H:\web\Python> & python h:\web\Python\01.MySql\db.py 1 2 50
转出帐号=1
转入帐号=2
金额=50
check_acct_available:select * from account where acctid=''
check_acct_available:select * from account where acctid=''
has_enough_money:select * from account where acctid='' and money>50
transfer出现异常:帐号1没有足够的金额
main出现异常:帐号1没有足够的金额

参考:

https://www.cnblogs.com/Erick-L/p/7106816.html

Python-PostgreSQL的使用的更多相关文章

  1. Python PostgreSQL Psycopg2

    [转] http://daigong.iteye.com/blog/901160 Python如果要操作Postgresql,需要一个API,这就需要Psycopg2 1. 链接PostgreSQL并 ...

  2. 我终于学会了使用python操作postgresql

    一 前言 这篇文章不仅适合pgsql,更适合mysql,思路都是一致的,如果读者学会使用psycopg2操作pgsql,那么使用PyMySQL 操作mysql也是很简单:本篇文章涵盖内容广泛,提供的操 ...

  3. PostgreSQL系列一:PostgreSQL简介与安装

    一.PostgreSQL简介     1.1 PostgreSQL概述             PostgreSQL数据库是目前功能最强大的开源数据库,支持丰富的数据类型(如JSON和JSONB类型. ...

  4. python 第三方模块 转 https://github.com/masterpy/zwpy_lst

    Chardet,字符编码探测器,可以自动检测文本.网页.xml的编码. colorama,主要用来给文本添加各种颜色,并且非常简单易用. Prettytable,主要用于在终端或浏览器端构建格式化的输 ...

  5. PostgreSQL Hardware Performance Tuning

    Bruce Momjian POSTGRESQL is an object-relational database developed on the Internet by a group of de ...

  6. python第三方库,你要的这里都有

    Python的第三方库多的超出我的想象. python 第三方模块 转 https://github.com/masterpy/zwpy_lst   Chardet,字符编码探测器,可以自动检测文本. ...

  7. Python 库,资源

    库名称简介 Chardet字符编码探测器,可以自动检测文本.网页.xml的编码. colorama主要用来给文本添加各种颜色,并且非常简单易用. Prettytable主要用于在终端或浏览器端构建格式 ...

  8. [转]PostgreSQL源码结构

    PostgreSQL采用C/S(客户机/服务器)模式结构.应用层通过INET或者Unix Socket利用既定的协议与数据库服务器进行通信. 另外,还有一种‘Standalone Backend’使用 ...

  9. Life is short.,You need Python

    真棒Python  https://awesome-python.com/ 精选的Python框架,库,软件和资源的精选列表. 灵感来自awesome-php. 真棒Python 管理员面板 算法和设 ...

  10. 这几天加班熬夜把所有Python库整理了一遍,非常全面!

    库名称简介 Chardet 字符编码探测器,可以自动检测文本.网页.xml的编码.colorama 主要用来给文本添加各种颜色,并且非常简单易用.Prettytable 主要用于在终端或浏览器端构建格 ...

随机推荐

  1. 修改mysql错误日志级别

    show variables like '%log_warnings%'; 1代表开启warning信息,0代表关闭warning信息 set session log_warnings=0; set ...

  2. 在 Microsoft.VisualStudio.Setup.Engine.Install(Product product, String destination, CancellationToken token)无法在相同位置或现有实例“20cc4971”的子目录上安装指定实例“ebc82a8e”的解决方案

    在所在的安装目录根目录下搜索实例 如 20cc4971 将文件夹全部删除. 一般默认安装在C盘,所以在C盘搜索实例文件夹,将其全部删除.

  3. Spring Boot2(十四):单文件上传/下载,文件批量上传

    文件上传和下载在项目中经常用到,这里主要学习SpringBoot完成单个文件上传/下载,批量文件上传的场景应用.结合mysql数据库.jpa数据层操作.thymeleaf页面模板. 一.准备 添加ma ...

  4. SpringMVC面试题:什么是Servlet?

    一.什么是servlet? servlet是一个Java编写的程序,此程序是基于http协议的,在服务器端(如Tomcat)运行的,是按照servlet规范编写的一个Java类.客户端发送请求至服务器 ...

  5. java-org.springframework.core.convert.ConversionFailedException- 前端传string解析date异常

    关于SpringMVC前台日期作为实体类对象参数类型转换错误解决 异常信息: Field error in object 'tblHouse' on field 'houseTime': reject ...

  6. [leetcode] 63. Unique Paths II (medium)

    原题 思路: 用到dp的思想,到row,col点路径数量 : path[row][col]=path[row][col-1]+path[row-1][col]; 遍历row*col,如果map[row ...

  7. [leetcode] 406. Queue Reconstruction by Height (medium)

    原题 思路: 一开始完全没有思路..看了别人的思路才解出来. 先按照他们的高度从高到低(因为我后面用的从前往后遍历插入,当然也可以从低到高)排序,如果高度一样,那么按照k值从小到大排序. 排完序后我们 ...

  8. Apache Tomcat 绿色版安装Service(服务)

    1.配置CATALINA_HOME的环境变量:  变量名:CATALINA_HOME  值:tomcat安装或解压的根目录如:c:\Apache tomcat6.0 2.开始->运行->c ...

  9. 说说Java线程间通信

    序言 正文 [一] Java线程间如何通信? 线程间通信的目标是使线程间能够互相发送信号,包括如下几种方式: 1.通过共享对象通信 线程间发送信号的一个简单方式是在共享对象的变量里设置信号值:线程A在 ...

  10. cookbook_元编程

    1给函数添加一个包装 问题:给函数加一个外包装层,已添加额外的处理,例如,记录日志,计时统计等 解决方案:可以定义一个装饰器来包装函数 2编写装饰器时如何保存函数的元数据 问题:当一个函数被装饰器装饰 ...