Python学习笔记 - PostgreSQL的使用
一、安装PostgreSQL模块
pip install psycopg2
有时候会失败,多安装2次就好了(我是第二次成功了)。
二、数据库连接接口
由于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 ('1', '张三', 50); INSERT INTO `account` VALUES ('2', '李四', 150);
Python程序
# coding:utf8 import sysimport psycopg2 #PostgreSQL
class TransferMoney(object):def __init__(self, conn):self.conn = conndef check_acct_available(self, acctid):cursor = self.conn.cursor()try:sql = "select * from account where acctid='%s'" % acctidprint("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 edef 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')
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='1' check_acct_available:select * from account where acctid='2' has_enough_money:select * from account where acctid='1' and money>50 reduce_money:update account set money=money-50 where acctid='1' add_money:update account set money=money+50 where acctid='2' 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='1' check_acct_available:select * from account where acctid='2' has_enough_money:select * from account where acctid='1' and money>50 transfer出现异常:帐号1没有足够的金额 main出现异常:帐号1没有足够的金额
参考:
https://www.cnblogs.com/Erick-L/p/7106816.html
转载于:https://www.cnblogs.com/chuancheng/p/8456978.html
Python学习笔记 - PostgreSQL的使用相关推荐
- Python学习笔记:访问数据库
前言 最近在学习深度学习,已经跑出了几个模型,但Pyhton的基础不够扎实,因此,开始补习Python了,大家都推荐廖雪峰的课程,因此,开始了学习,但光学有没有用,还要和大家讨论一下,因此,写下这些帖 ...
- PYTHON学习笔记之(一)2020.08
PYTHON学习笔记之(一)2020.08 Python基础 数据类型 常见的列表.字典,以及元组.集合. 1 列表 list 1.1 列表转换字符串 stu = ['王一', '李二', '张三'] ...
- [python教程入门学习]python学习笔记(CMD执行文件并传入参数)
本文章向大家介绍python学习笔记(CMD执行文件并传入参数),主要包括python学习笔记(CMD执行文件并传入参数)使用实例.应用技巧.基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋 ...
- python学习笔记之编写readConfig读写配置文件
python学习笔记之编写readConfig读写配置文件_weixin_34055910的博客-CSDN博客
- Python学习笔记(十一)
Python学习笔记(十一): 生成器,迭代器回顾 模块 作业-计算器 1. 生成器,迭代器回顾 1. 列表生成式:[x for x in range(10)] 2. 生成器 (generator o ...
- Python学习笔记一简介及安装配置
Python学习笔记一 参考教程:廖雪峰官网https://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e54 ...
- python学习笔记目录
人生苦短,我学python学习笔记目录: week1 python入门week2 python基础week3 python进阶week4 python模块week5 python高阶week6 数据结 ...
- Python学习笔记(二):标准流与重定向
Python学习笔记(二):标准流与重定向 - SamWei - 博客园 Python学习笔记(二):标准流与重定向 Posted on 2012-02-19 22:36 SamWei 阅读(176) ...
- python 学习笔记 12 -- 写一个脚本获取城市天气信息
近期在玩树莓派,前面写过一篇在树莓派上使用1602液晶显示屏,那么可以显示后最重要的就是显示什么的问题了. 最easy想到的就是显示时间啊,CPU利用率啊.IP地址之类的.那么我认为呢,假设可以显示当 ...
最新文章
- Announcing the Updated NGINX and NGINX Plus Plug‑In for New Relic (Version 2)
- 第十六章、Raid及mdadm命令
- 导入新的一个android项目抱错
- linux函数输入,go编程输入函数
- android 获取sd卡目录失败_树莓派对SD卡的大小,速度有哪些要求?
- 移动端 爬虫工具 与 方法 介绍
- java 数值变量_Java 中数值变量赋值问题
- python中使用cv2.findContours返回值too many values to unpack (expected 2)错误如何解决
- Posix共享内存区
- iOS 证书, provision profile作用
- fw-cloud-framework项目配置、启动问题
- 修改input file 文件上传的样式
- ArcGIS10.8安装(附最新<2022年10月29日>下载地址)
- visio 2013破解
- 安装驱动省心办法:驱动总裁
- 数字基带通信系统的实现流程
- 使用Dependency Walker对模块进行故障排除
- 一卡通管理系统总体设计
- 【MOS管知识汇总】分类、区分、寄生二极管、导通条件、开关电路、串联电阻
- excel转vcf 易语言免费版