一、安装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. CAD2014学习笔记-图层图案图块

    基于 虎课网huke88.com CAD教程 对象特性 选择对象点击特性栏/或右键点击特性 颜色:color 图层 线型:线的类型,如点状线.虚线等,若不改变则默认新建的线为该类型 线型比例:不同类型 ...

  2. MongoDB基础教程[菜鸟教程整理]

    MongoDB基础教程 ======================================================================================== ...

  3. JavaScript函数及闭包

    前面一片文章讲到过一点函数,了解到每声明一个函数就会产生一个作用域.而外面的作用域访问不了里面的作用域(把里面的变量和函数隐藏起来),而里面的可以访问到外面的.对于隐藏变量和函数是一个非常有用的技术. ...

  4. [sublime3] 在linux下的终端中使用sublime3打开文件

    通过ln命令创建软连接实现 echo $PATH 查看路径 例 我的路径是: /home/rh/anaconda3/bin:/home/rh/bin:/home/rh/.local/bin:/usr/ ...

  5. 什么是WebP以及如何在WordPress中使用WebP图像

    图像通常是缓慢加载网页的最大原因之一.它们不仅减慢了加载时间,而且还可以占用服务器上的大量空间和资源.仔细选择文件类型并压缩它们有助于降低加载速度,但它们只能在图像质量受损之前进行优化.另一种选择是使 ...

  6. IT技术人员的自我修养

    1. 前言        在IT领域摸爬滚打多年,从一个普通程序员到技术主管,到技术经理,再到技术总监,踩过不少坑.加过不少班,也背过不少锅,在提升自身技术能力与管理能力的同时,也一直在思考,作为IT ...

  7. mongodb的索引原理

    首先说一下为什么要有索引,大家都知道mongdb是非关系型文档类型数据库,用过的人都有同一种感受,查询的效率太低,当你想提高查询效率的时候可以就需要使用索引了. 哈哈,本来想写一篇的,在网上看到了一篇 ...

  8. 脱壳系列_2_IAT加密壳_详细版解法1(含脚本)

    1 查看壳程序信息 使用ExeInfoPe 分析: 发现这个壳的类型没有被识别出来,Vc 6.0倒是识别出来了,Vc 6.0的特征是 入口函数先调用GetVersion() 2 用OD找OEP 拖进O ...

  9. 【iOS】获取项目名和版本号

    iOS 开发中,有时候需要获取项目名和版本号,示例代码如下: -(void)getProjectNameAndVersion{ appName = [[[NSBundle mainBundle] in ...

  10. Linux系统下增加LV(逻辑卷)容量 、Linux系统下减少LV(逻辑卷)容量

    查看文件系统现有lv_test容量,总计4.9G,已使用3% 命令 df -h   查看现有磁盘情况,我们发现磁盘sdb共有1305个柱面,每个柱面大小是8225280 bytes (大约8M).有一 ...