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之重回函数
Oct 10 Python
Python 中 Virtualenv 和 pip 的简单用法详解
Aug 18 Python
Python通过matplotlib绘制动画简单实例
Dec 13 Python
Python3中exp()函数用法分析
Feb 19 Python
python数据类型之间怎么转换技巧分享
Aug 20 Python
python多进程并行代码实例
Sep 30 Python
使用Python来做一个屏幕录制工具的操作代码
Jan 18 Python
Python+appium框架原生代码实现App自动化测试详解
Mar 06 Python
Python运行异常管理解决方案
Mar 09 Python
PyQt5多线程防卡死和多窗口用法的实现
Sep 15 Python
python实现测试工具(一)——命令行发送get请求
Oct 19 Python
Python手拉手教你爬取贝壳房源数据的实战教程
May 21 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新手上路(四)
2006/10/09 PHP
php使用GD2绘制几何图形示例
2017/02/15 PHP
详解PHP中的序列化、反序列化操作
2017/03/21 PHP
Yii 2中的load()和save()示例详解
2017/08/03 PHP
利用PHPStorm如何开发Laravel应用详解
2017/08/30 PHP
JavaScript格式化日期时间的方法和自定义格式化函数示例
2014/04/04 Javascript
jQuery中事件对象e的事件冒泡用法示例介绍
2014/04/25 Javascript
node.js使用require()函数加载模块
2014/11/26 Javascript
JS数组排序技巧汇总(冒泡、sort、快速、希尔等排序)
2015/11/24 Javascript
jQuery ajax 当async为false时解决同步操作失败的问题
2016/11/18 Javascript
详解js中常规日期格式处理、月历渲染和倒计时函数
2016/12/28 Javascript
Vue.js原理分析之observer模块详解
2017/02/17 Javascript
underscore之Chaining_动力节点Java学院整理
2017/07/10 Javascript
Underscore之Array_动力节点Java学院整理
2017/07/10 Javascript
vue vue-Router默认hash模式修改为history需要做的修改详解
2018/09/13 Javascript
vue中的mescroll搜索运用及各种填坑处理
2019/10/30 Javascript
Javascript执行流程细节原理解析
2020/05/14 Javascript
老生常谈python的私有公有属性(必看篇)
2017/06/09 Python
Python使用Phantomjs截屏网页的方法
2018/05/17 Python
python的格式化输出(format,%)实例详解
2018/06/01 Python
详解Python中的正则表达式
2018/07/08 Python
浅谈Pycharm调用同级目录下的py脚本bug
2018/12/03 Python
python 获取图片分辨率的方法
2019/01/08 Python
Python实现从N个数中找到最大的K个数
2020/04/02 Python
安装并免费使用Pycharm专业版(学生/教师)
2020/09/24 Python
CSS3属性选择符介绍
2008/10/17 HTML / CSS
使用CSS3制作饼状旋转载入效果的实例
2015/06/23 HTML / CSS
借助HTML5 Canvas API制作一个简单的猜字游戏
2016/03/25 HTML / CSS
波兰家居和花园家具专家:4Home
2019/05/26 全球购物
八年级语文教学反思
2014/02/11 职场文书
经济信息系毕业生自荐信范文
2014/03/15 职场文书
中华魂放飞梦想演讲稿
2014/08/26 职场文书
2014年最新版离婚协议书范本
2014/11/25 职场文书
因家庭原因离职的辞职信范文
2015/05/12 职场文书
担保书格式范文
2015/09/22 职场文书
Python中time标准库的使用教程
2022/04/13 Python