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对两个有序列表进行合并和排序的例子
Jun 13 Python
python socket 超时设置 errno 10054
Jul 01 Python
Python模拟用户登录验证
Sep 11 Python
pycharm修改界面主题颜色的方法
Jan 17 Python
强悍的Python读取大文件的解决方案
Feb 16 Python
selenium跳过webdriver检测并模拟登录淘宝
Jun 12 Python
pandas进行时间数据的转换和计算时间差并提取年月日
Jul 06 Python
Python中list的交、并、差集获取方法示例
Aug 01 Python
python线程信号量semaphore使用解析
Nov 30 Python
Docker部署Python爬虫项目的方法步骤
Jan 19 Python
Python实现栈的方法详解【基于数组和单链表两种方法】
Feb 22 Python
python爬虫beautifulsoup库使用操作教程全解(python爬虫基础入门)
Feb 19 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
文件上传程序的全部源码
2006/10/09 PHP
PHP用mysql数据库存储session的代码
2010/03/05 PHP
PHP删除HTMl标签的三种解决方法
2013/06/30 PHP
javascript 24小时弹出一次的代码(利用cookies)
2009/09/03 Javascript
jquery.cookie用法详细解析
2013/12/18 Javascript
使用jquery局部刷新(jquery.load)从数据库取出数据
2014/01/22 Javascript
node.js中的console.dir方法使用说明
2014/12/10 Javascript
JavaScript实现自动变换表格边框颜色
2015/05/08 Javascript
JavaScript实现把数字转换成中文
2015/06/29 Javascript
jQuery实现信息提示框(带有圆角框与动画)效果
2015/08/07 Javascript
jQuery实现带延迟的二级tab切换下拉列表效果
2015/09/01 Javascript
Vue2.0实现将页面中表格数据导出excel的实例
2017/08/09 Javascript
vue使用mint-ui实现下拉刷新和无限滚动的示例代码
2017/11/06 Javascript
vue二级路由设置方法
2018/02/09 Javascript
node错误处理与日志记录的实现
2018/12/24 Javascript
CountUp.js数字滚动插件使用方法详解
2019/10/17 Javascript
[50:29]2014 DOTA2华西杯精英邀请赛 5 24 DK VS iG
2014/05/26 DOTA
[58:11]守擂赛第二周擂主赛 DeMonsTer vs Leopard
2020/04/28 DOTA
跨平台python异步回调机制实现和使用方法
2013/11/26 Python
Python中基本的日期时间处理的学习教程
2015/10/16 Python
Python简单定义与使用字典dict的方法示例
2017/07/25 Python
python3 实现对图片进行局部切割的方法
2018/12/05 Python
浅谈python的深浅拷贝以及fromkeys的用法
2019/03/08 Python
Python中url标签使用知识点总结
2020/01/16 Python
使用opencv识别图像红色区域,并输出红色区域中心点坐标
2020/06/02 Python
python 负数取模运算实例
2020/06/03 Python
英国男士时尚购物网站:Stuarts London
2017/10/22 全球购物
武汉高蓝德国际.net机试
2016/06/24 面试题
GC是什么?为什么要有GC?
2013/12/08 面试题
出口公司经理求职简历中的自我评价
2013/10/13 职场文书
音乐器材管理制度
2014/01/31 职场文书
营业用房租赁协议书
2014/11/26 职场文书
财务负责人岗位职责
2015/02/03 职场文书
职工趣味运动会开幕词
2016/03/04 职场文书
python字典进行运算原理及实例分享
2021/08/02 Python
教你使用Ubuntu搭建DNS服务器
2022/09/23 Servers