一、安装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. android_activity_研究(一)

    android中活动的概念(activity)是一个很重要的东东.这里有很多东东值得好好研究.最好的研究来源当然是官网啦,所以本人这里写一点对官网文章的研究心得. 一.活动(activity)的概念 ...

  2. 20131207-ADO.NET-第十六天

    [1]快捷键 工具箱:ctrl+w+x 首字母定位控件范围 属性:F4 或ctrl+w+p Tab跳转 ,home 与end也有效 [2]连接字符串 string str = "Data S ...

  3. NetworkError: Failed to execute 'send' on 'XMLHttpRequest': Failed to load xxxx错误解决方法

    在开发项目的过程中,和后端对接,我们使用是一个成熟的集成很全面的架构JHipster.后端为java spring-boot 前端ts+react,需求是有一个需要在页面里嵌套iframe的需求.然后 ...

  4. PCB SQL SERVER 数据库阻塞进程关系以思维导图方式呈现的实现方法

    最近公司服务数据库同步机制常发生阻塞,时不时的导致PCB工程系统卡死现象,只有找到阻塞源头并处理掉,才以消除阻塞,但数据库中查看会话阻塞是通过二维表方式展示的父子会话进程ID的,是很难清楚的展示各会话 ...

  5. ISTQB名词辨析

    测试规程说明(Test Procedure Specification) 规定了执行测试的一系列行为的文档,也称为测试脚本或测试剧本.

  6. 反⑨baka拖更大队:临时约法

    本团队中将不时发起团队讨论报道⑨baka无良~ 某无良⑨baka一直拖更引起广大人民群众不满 文文新闻:https://www.luogu.org/discuss/show/52654 反⑨baka的 ...

  7. 在springboot中使用swagger2

    1.在springboot中使用swagger的话,首先在pom文件中引入依赖 <!-- https://mvnrepository.com/artifact/io.springfox/spri ...

  8. md文档的书写《三》

    markdown语法 官网 这是标题 "#加空格" 是标题,通常可以设置六级标题. 内容下 空格是换行 列表 无序列表:使用" - + * "任何一种加空格都可 ...

  9. APP爬虫(2)把小姐姐的图片down下来

    APP爬虫(1)想学新语言,又没有动力,怎么办? 书接上文.使用appium在帖子列表界面模拟上划动作,捕捉不到列表的规律.上划结束后,列表只能获取到屏幕呈现的部分,而且下标还是从0开始的. 根据酸奶 ...

  10. 学习LayUI时自研的表单参数校验框架

    开发背景&痛点:每次写前端的表单的时候需要对表单里用户填写的内容进行校验,减少服务器压力,提前对已知错误对用户提示.每次会要写很多的if else等等对输入框中的内容进行判断,并对为空.格式不 ...