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文件操作类操作实例详解
Jul 11 Python
基于python中的TCP及UDP(详解)
Nov 06 Python
Tensorflow卷积神经网络实例
May 24 Python
根据DataFrame某一列的值来选择具体的某一行方法
Jul 03 Python
python使用tornado实现简单爬虫
Jul 28 Python
django与小程序实现登录验证功能的示例代码
Feb 19 Python
正则给header的冒号两边参数添加单引号(Python请求用)
Aug 09 Python
Python学习笔记之While循环用法分析
Aug 14 Python
python操作gitlab API过程解析
Dec 27 Python
Python如何实现后端自定义认证并实现多条件登陆
Jun 22 Python
python操作链表的示例代码
Sep 27 Python
讲解Python实例练习逆序输出字符串
May 06 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进行MySQL删除记录操作代码
2008/06/07 PHP
zend Framework中的Layout(模块化得布局)详解
2013/06/28 PHP
php ci框架中加载css和js文件失败的原因及解决方法
2014/07/29 PHP
PHP内核探索之解释器的执行过程
2015/12/22 PHP
php进行ip地址掩码运算处理的方法
2016/07/11 PHP
深入document.write()与HTML4.01的非成对标签的详解
2013/05/08 Javascript
浅析JQuery获取和设置Select选项的常用方法总结
2013/07/04 Javascript
ff下JQuery无法监听input的keyup事件的解决方法
2013/12/12 Javascript
JS实现关键字搜索时的相关下拉字段效果
2014/08/05 Javascript
微信小程序 配置文件详细介绍
2016/12/14 Javascript
详解微信小程序——自定义圆形进度条
2016/12/29 Javascript
微信小程序实现导航栏选项卡效果
2020/06/19 Javascript
JavaScript实现无限级递归树的示例代码
2019/03/29 Javascript
nodejs log4js 使用详解
2019/05/31 NodeJs
解决VUE 在IE下出现ReferenceError: Promise未定义的问题
2020/11/07 Javascript
python list转dict示例分享
2014/01/28 Python
Python中获取对象信息的方法
2015/04/27 Python
浅谈Python 中整型对象的存储问题
2016/05/16 Python
详解用python写一个抽奖程序
2019/05/10 Python
django的ORM操作 增加和查询
2019/07/26 Python
使用Django和Postgres进行全文搜索的实例代码
2020/02/13 Python
浅谈图像处理中掩膜(mask)的意义
2020/02/19 Python
python实现字符串和数字拼接
2020/03/02 Python
如何从csv文件构建Tensorflow的数据集
2020/09/21 Python
html5 兼容IE6结构的实现代码
2012/05/14 HTML / CSS
日本高端护肤品牌:Tatcha
2016/08/29 全球购物
中专毕业生自我鉴定范文
2013/11/09 职场文书
物业电工岗位职责
2013/11/20 职场文书
外贸业务员岗位职责
2013/11/24 职场文书
合作经营协议书
2014/04/17 职场文书
工作失误检讨书(经典集锦版)
2014/10/17 职场文书
2014年实习班主任工作总结
2014/11/08 职场文书
2019年中,最受大众欢迎的6本新书
2019/08/07 职场文书
详解缓存穿透击穿雪崩解决方案
2021/05/28 Redis
AudioContext 实现音频可视化(web技术分享)
2022/02/24 Javascript
win11开机发生死循环重启怎么办?win11开机发生死循环重启解决方法
2022/08/05 数码科技