Python-PostgreSQL的使用
一、安装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的使用的更多相关文章
- Python PostgreSQL Psycopg2
[转] http://daigong.iteye.com/blog/901160 Python如果要操作Postgresql,需要一个API,这就需要Psycopg2 1. 链接PostgreSQL并 ...
- 我终于学会了使用python操作postgresql
一 前言 这篇文章不仅适合pgsql,更适合mysql,思路都是一致的,如果读者学会使用psycopg2操作pgsql,那么使用PyMySQL 操作mysql也是很简单:本篇文章涵盖内容广泛,提供的操 ...
- PostgreSQL系列一:PostgreSQL简介与安装
一.PostgreSQL简介 1.1 PostgreSQL概述 PostgreSQL数据库是目前功能最强大的开源数据库,支持丰富的数据类型(如JSON和JSONB类型. ...
- python 第三方模块 转 https://github.com/masterpy/zwpy_lst
Chardet,字符编码探测器,可以自动检测文本.网页.xml的编码. colorama,主要用来给文本添加各种颜色,并且非常简单易用. Prettytable,主要用于在终端或浏览器端构建格式化的输 ...
- PostgreSQL Hardware Performance Tuning
Bruce Momjian POSTGRESQL is an object-relational database developed on the Internet by a group of de ...
- python第三方库,你要的这里都有
Python的第三方库多的超出我的想象. python 第三方模块 转 https://github.com/masterpy/zwpy_lst Chardet,字符编码探测器,可以自动检测文本. ...
- Python 库,资源
库名称简介 Chardet字符编码探测器,可以自动检测文本.网页.xml的编码. colorama主要用来给文本添加各种颜色,并且非常简单易用. Prettytable主要用于在终端或浏览器端构建格式 ...
- [转]PostgreSQL源码结构
PostgreSQL采用C/S(客户机/服务器)模式结构.应用层通过INET或者Unix Socket利用既定的协议与数据库服务器进行通信. 另外,还有一种‘Standalone Backend’使用 ...
- Life is short.,You need Python
真棒Python https://awesome-python.com/ 精选的Python框架,库,软件和资源的精选列表. 灵感来自awesome-php. 真棒Python 管理员面板 算法和设 ...
- 这几天加班熬夜把所有Python库整理了一遍,非常全面!
库名称简介 Chardet 字符编码探测器,可以自动检测文本.网页.xml的编码.colorama 主要用来给文本添加各种颜色,并且非常简单易用.Prettytable 主要用于在终端或浏览器端构建格 ...
随机推荐
- Maven(一)Maven 的概念和安装
Maven 的概念和安装 Maven 是什么 首先 Maven 肯定是一个造福人类的好东西,它可以省去我们构建项目中引入 jar 包时的麻烦,还有利于项目的模块化开发等等等好处.在如今项目中大体都是使 ...
- UVA11988 【Broken Keyboard (a.k.a. Beiju Text)】:题解
题目链接:https://www.luogu.org/problemnew/show/UVA11988 这题虽说是和链表有关的模拟,但其实并不是很需要啊,但蒟蒻用了(说的好听是练手,说的难听是太弱), ...
- 小白之入口即化——十分钟看懂while循环,字符串格式化,运算符
while循环 while循环-死循环 while空格+条件+冒号 缩进+循环体 3.打断死循环 break--终止当前循环 while True: print(123) print(234) bre ...
- 题解 P2949 【[USACO09OPEN]工作调度Work Scheduling】
P2949 [USACO09OPEN]工作调度Work Scheduling 题目标签是单调队列+dp,萌新太弱不会 明显的一道贪心题,考虑排序先做截止时间早的,但我们发现后面可能会出现价值更高却没有 ...
- C#3.0新增功能09 LINQ 基础01 语言集成查询
连载目录 [已更新最新开发文章,点击查看详细] 语言集成查询 (LINQ) 是一系列直接将查询功能集成到 C# 语言的技术统称. 数据查询历来都表示为简单的字符串,没有编译时类型检查或 Inte ...
- [leetcode] 45. Jump Game II(hard)
原题 题意: 是Jump Game的衍生题(题解),题意求跳到最后一格所需最少步数,(默认所测数据永远可以跳到最后一格). 思路: 利用贪心,遍历数组,记录在每一步可跳跃到的最大区域. 1.当前步数 ...
- C#后台HttpWebRequest模拟跨域Ajax请求,注册Windows服务到服务器上
项目需求,暂且叫A.B公司吧.我们公司需要从A公司哪里读取机器上的数据,放到我们数据库中.然后再将数据库中存的数据,提供一个接口,B公司来调用,大概这个意思. 好了,言归正传.这个是之前做好的界面,用 ...
- MyEclipse 2016 Stable 1.0破解教程
一.下载所需文件 1. Windows最新版: MyEclipse 2016 Stable 1.0离线安装包(文件大小:1.52GB)--完整安装包,无需在线下载http://pan.baidu.co ...
- linux初学者-mail篇
linux初学者-mail篇 邮件是在生活中比较常用的一个工具,在linux系统中的邮件也是.在linux中,邮件的发送所用的服务时postfix,邮件的接收所用的服务是pop(110端口).ima ...
- HPU暑期集训积分赛2
A. 再战斐波那契 单点时限: 1.0 sec 内存限制: 512 MB 小z 学会了斐波那契和 gcd 后,老师又给他出了个难题,求第N个和第M个斐波那契数的最大公约数,这可难倒了小z ,不过在小z ...