Python学习笔记 - MySql的使用
一、安装MySql模块
Python2.X
pip install MySQLdb
Python3.X
pip install pymysql
二、数据库连接接口
由于Python统一了数据库连接的接口,所以 pymysql 和 MySQLdb 在使用方式上是类似的:
pymysql.Connect()参数说明
host(str): MySQL服务器地址
port(int): MySQL服务器端口号
user(str): 用户名
passwd(str): 密码
db(str): 数据库名称
charset(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 pymysql 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) # 连接数据库
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没有足够的金额


参考:
http://www.cnblogs.com/woider/p/5926744.html
Python学习笔记 - MySql的使用的更多相关文章
- Python学习笔记——MySQL的基本操作(2)
1 运算符操作(配合查.修.删操作) 数据库的语法结构 查:select * from 表名 where 字段名 运算符 数字/字符; 改:update 表名 set 字段名=值,... wher ...
- python学习笔记--Django入门四 管理站点--二
接上一节 python学习笔记--Django入门四 管理站点 设置字段可选 编辑Book模块在email字段上加上blank=True,指定email字段为可选,代码如下: class Autho ...
- Python学习笔记进阶篇——总览
Python学习笔记——进阶篇[第八周]———进程.线程.协程篇(Socket编程进阶&多线程.多进程) Python学习笔记——进阶篇[第八周]———进程.线程.协程篇(异常处理) Pyth ...
- python学习笔记目录
人生苦短,我学python学习笔记目录: week1 python入门week2 python基础week3 python进阶week4 python模块week5 python高阶week6 数据结 ...
- python学习笔记整理——字典
python学习笔记整理 数据结构--字典 无序的 {键:值} 对集合 用于查询的方法 len(d) Return the number of items in the dictionary d. 返 ...
- VS2013中Python学习笔记[Django Web的第一个网页]
前言 前面我简单介绍了Python的Hello World.看到有人问我搞搞Python的Web,一时兴起,就来试试看. 第一篇 VS2013中Python学习笔记[环境搭建] 简单介绍Python环 ...
- python学习笔记之module && package
个人总结: import module,module就是文件名,导入那个python文件 import package,package就是一个文件夹,导入的文件夹下有一个__init__.py的文件, ...
- python学习笔记(六)文件夹遍历,异常处理
python学习笔记(六) 文件夹遍历 1.递归遍历 import os allfile = [] def dirList(path): filelist = os.listdir(path) for ...
- python学习笔记--Django入门0 安装dangjo
经过这几天的折腾,经历了Django的各种报错,翻译的内容虽然不错,但是与实际的版本有差别,会出现各种奇葩的错误.现在终于找到了解决方法:查看英文原版内容:http://djangobook.com/ ...
随机推荐
- B-树 C++模板类封装(有图有真相)
定义: 一棵m阶B-树是拥有以下性质的多路查找树: 1.非叶子结点的根结点至少拥有两棵子树: 2.每一个非根且非叶子的结点含有k-1个关键字以及k个子树,其中⌈m/2⌉≤k≤m: 3.每一个叶子结点都 ...
- 20165101刘天野 2017-2018-2 《Java程序设计》第7周学习总结
#20165101刘天野 2017-2018-2 <Java程序设计>第7周学习总结 教材学习内容总结 第十一章JDBC与MySQL数据库 JDBC简介 JDBC(Java Databas ...
- OC_内存管理(二)对象复制、循环引用问题、自动释放池
循环调用: 1.循环引用的问题 两个对象A.B,有可能会出现特殊情况:A中包含B的实例变量:B中也包含A的实例变量,如果这两个实例变量都是强引用(A有着B的实例变量所有权,B也有A的实例变量所有权 ...
- SQL Server获取数据库的当前连接状态
SELECT * FROM [Master].[dbo].[SYSPROCESSES] WHERE [DBID]=(SELECT [DBID] FROM [Master].[dbo].[SYSDATA ...
- Eclipse常用插件安装_PropertiesEditor
properties文件在项目中多用做i18n国际化支持的配置文件,在properties文件中出现的中文信息都要转换为Unicode文本,一般的做法都是使用JDK自带的native2ascii工具进 ...
- poj 1679 The Unique MST 【次小生成树+100的小数据量】
题目地址:http://poj.org/problem?id=1679 2 3 3 1 2 1 2 3 2 3 1 3 4 4 1 2 2 2 3 2 3 4 2 4 1 2 Sample Outpu ...
- Java线程池ExecutorService和CountDownLatch的小例子
import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java ...
- SpringMVC中使用ModelAndView遇到的问题
本文记录我在SpringMVC中使用ModelAndView,添加模型数据到ModelAndView中时遇到的问题: 1.jsp页面用EL表达式来获取值时直接显示EL表达式,JSP不解析EL表达式: ...
- spring启动加载类,手动加载bean
方法一: public final class Assembler implements BeanFactoryPostProcessor { private static ConfigurableL ...
- iframe标签的子父页面调用函数和属性
在使用iframe标签时,总想通过子页面调用父页面的一些方法和属性.今天终于发现了. 1在父页面写一个函数 //让子页面来调用此方法,控制导航栏 function childfunc(){ alert ...