python实现的MySQL增删改查操作实例小结


Posted in Python onDecember 19, 2018

本文实例总结了python实现的MySQL增删改查操作。分享给大家供大家参考,具体如下:

代码片段一

连接并执行sql

#encoding:UTF-8
import MySQLdb
conn = MySQLdb.Connect(
  host = '127.0.0.1',
  port = 3306,
  user = 'root',
  passwd='123456',
  db='imooc',
  charset='utf8'
)
cursor = conn.cursor()
print conn
print cursor
sql = "select * from user"
cursor.execute(sql) #执行

取数据

print cursor.rowcount
#取数据
#fetchone()获取一条数据
#fetchany(3)获取多条
#fetchall()#获取客户缓冲区的所有数据
# rs = cursor.fetchone()
# print rs
#
# rs = cursor.fetchmany(2)
# print rs
#
# rs = cursor.fetchall()
# print rs
# rs = cursor.fetchall()
# for row in rs:
#   print "userid=%s,username=%s" % row

更新数据库

# sql_insert = "insert into user(userid,username) values(10,'name10')"
# sql_update = "update user set username='name91' where userid=9"
# sql_delete = "delete from user where userid<3"
# cursor.execute(sql_insert)
# cursor.execute(sql_update)
# cursor.execute(sql_delete)
# #执行完后提交
# conn.commit()
# #发生异常时回滚
# try:
#   sql_insert = "insert into user(userid,username) values(10,'name10')"
#   sql_update = "update user set username='name91' where userid=9"
#   sql_delete = "delete from user where userid<3"
#   cursor.execute(sql_insert)
#   cursor.execute(sql_update)
#   cursor.execute(sql_delete)
#   conn.commit()
# except Exception as e:
#   print e
#   conn.rollback()
cursor.close()
conn.close()

代码片段2 银行实例

#coding:UTF-8
import sys
import MySQLdb
class TransferMoney(object):
  def __init__(self,conn):
    self.conn = conn
  def tranfer(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()
      raise e
  def check_acct_available(self, acctid):
    cursor = self.conn.cursor()
    try:
      sql = "select * from account where acctid=%s"%acctid
      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)
      cursor.execute(sql)
      print "has_enough_money:"+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)
      cursor.execute(sql)
      print "reduce_money:"+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)
      cursor.execute(sql)
      print "reduce_money:" + sql
      if cursor.rowcount != 1:
        raise Exception("账号%s加款失败" % acctid)
    finally:
      cursor.close()
if __name__ == "__main__":
  source_acctid = sys.argv[1]
  target_acctid = sys.argv[2]
  money = sys.argv[3]
  conn = MySQLdb.Connect(
    host='127.0.0.1',
    port=3306,
    user='root',
    passwd='123456',
    db='imooc',
    charset='utf8'
  )
  tr_money = TransferMoney(conn)
  try:
    tr_money.tranfer(source_acctid,target_acctid,money)
  except Exception as e:
    print "出现问题了" + str(e)
  finally:
    conn.close()

希望本文所述对大家Python程序设计有所帮助。

Python 相关文章推荐
python和shell实现的校验IP地址合法性脚本分享
Oct 23 Python
Python简单日志处理类分享
Feb 14 Python
简单的连接MySQL与Python的Bottle框架的方法
Apr 30 Python
Python列表list内建函数用法实例分析【insert、remove、index、pop等】
Jul 24 Python
Python 实现淘宝秒杀的示例代码
Jan 02 Python
详谈python中冒号与逗号的区别
Apr 18 Python
python 异或加密字符串的实例
Oct 14 Python
Python中*args和**kwargs的区别详解
Sep 17 Python
200行python代码实现贪吃蛇游戏
Apr 24 Python
Python数据可视化实现漏斗图过程图解
Jul 20 Python
详解Python中__new__方法的作用
Mar 31 Python
python如何读取和存储dict()与.json格式文件
Jun 25 Python
python3 http提交json参数并获取返回值的方法
Dec 19 #Python
python3.6使用urllib完成下载的实例
Dec 19 #Python
使用urllib库的urlretrieve()方法下载网络文件到本地的方法
Dec 19 #Python
对python内置map和six.moves.map的区别详解
Dec 19 #Python
对python中的six.moves模块的下载函数urlretrieve详解
Dec 19 #Python
python爬虫URL重试机制的实现方法(python2.7以及python3.5)
Dec 18 #Python
对python3标准库httpclient的使用详解
Dec 18 #Python
You might like
php后台多用户权限组思路与实现程序代码分享
2012/02/13 PHP
PHP fgetcsv 定义和用法(附windows与linux下兼容问题)
2012/05/29 PHP
深入apache配置文件httpd.conf的部分参数说明
2013/06/28 PHP
php实现的ping端口函数实例
2014/11/12 PHP
配置php.ini实现PHP文件上传功能
2014/11/27 PHP
PHP获取数组最后一个值的2种方法
2015/01/21 PHP
PHP获取当前执行php文件名的代码
2017/03/02 PHP
PHP5.5新特性之yield理解与用法实例分析
2019/01/11 PHP
php设计模式之原型模式分析【星际争霸游戏案例】
2020/03/23 PHP
模仿jQuery each函数的链式调用
2009/07/22 Javascript
php与js的区别是什么
2013/08/05 Javascript
我的Node.js学习之路(三)--node.js作用、回调、同步和异步代码 以及事件循环
2014/07/06 Javascript
jquery实现多行文字图片滚动效果示例代码
2014/10/10 Javascript
JavaScript中使用Callback控制流程介绍
2015/03/16 Javascript
详解AngularJS的通信机制
2015/06/18 Javascript
js实现跨域的多种方法
2015/12/25 Javascript
详解Backbone.js框架中的模型Model与其集合collection
2016/05/05 Javascript
jQuery轻松实现表格的隔行变色和点击行变色的实例代码
2016/05/09 Javascript
移动端手指放大缩小插件与js源码
2017/05/22 Javascript
认识jQuery的Promise的具体使用方法
2017/10/10 jQuery
Node.js npm命令运行node.js脚本的方法
2018/10/10 Javascript
layui 对弹窗 form表单赋值的实现方法
2019/09/04 Javascript
JS控制GIF图片的停止与显示
2019/10/24 Javascript
原生JavaScript实现刮刮乐
2020/09/29 Javascript
[01:00]一分钟回顾2018DOTA2亚洲邀请赛现场活动
2018/04/07 DOTA
Python中http请求方法库汇总
2016/01/06 Python
python基础入门学习笔记(Python环境搭建)
2016/01/13 Python
对python遍历文件夹中的所有jpg文件的实例详解
2018/12/08 Python
python如何实现异步调用函数执行
2019/07/08 Python
pytorch: Parameter 的数据结构实例
2019/12/31 Python
将pymysql获取到的数据类型是tuple转化为pandas方式
2020/05/15 Python
户籍证明的格式
2014/01/13 职场文书
工艺员岗位职责
2014/02/11 职场文书
师范生求职信
2014/06/14 职场文书
2014超市双十一活动策划方案
2014/09/29 职场文书
家装业务员岗位职责
2015/04/03 职场文书