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使用Flask框架获取用户IP地址的方法
Mar 21 Python
Python中使用logging模块打印log日志详解
Apr 05 Python
在Python中使用base64模块处理字符编码的教程
Apr 28 Python
python制作爬虫爬取京东商品评论教程
Dec 16 Python
Django数据库操作的实例(增删改查)
Sep 04 Python
Pyspider中给爬虫伪造随机请求头的实例
May 07 Python
python实现NB-IoT模块远程控制
Jun 20 Python
详解python爬虫系列之初识爬虫
Apr 06 Python
Python+Opencv实现把图片、视频互转的示例
Dec 17 Python
Python 数据可视化之Bokeh详解
Nov 02 Python
Python Matplotlib库实现画局部图
Nov 17 Python
python实现商品进销存管理系统
May 30 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/12/06 PHP
ThinkPHP进程计数类Process用法实例详解
2015/09/25 PHP
php设计模式之抽象工厂模式分析【星际争霸游戏案例】
2020/01/23 PHP
js 面向对象的技术创建高级 Web 应用程序
2010/02/25 Javascript
纯js写的分页表格数据为json串
2014/02/18 Javascript
node.js中的console.dir方法使用说明
2014/12/10 Javascript
基于javascript制作经典传统的拼图游戏
2016/03/22 Javascript
关于JS中的apply,call,bind的深入解析
2016/04/05 Javascript
javascript中的 object 和 function小结
2016/08/14 Javascript
关于Javascript中defer和async的区别总结
2016/09/20 Javascript
JS实现加载和读取XML文件的方法详解
2017/04/24 Javascript
Node.js微信 access_token ( jsapi_ticket ) 存取与刷新的示例
2017/09/30 Javascript
最实用的JS数组函数整理
2017/12/05 Javascript
vue动画之点击按钮往上渐渐显示出来的实例
2018/09/29 Javascript
简谈创建React Component的几种方式
2019/06/15 Javascript
javascript 原型与原型链的理解及应用实例分析
2020/02/10 Javascript
python统计cpu利用率的方法
2015/06/02 Python
在Python中实现替换字符串中的子串的示例
2018/10/31 Python
python 获取页面表格数据存放到csv中的方法
2018/12/26 Python
50行Python代码实现视频中物体颜色识别和跟踪(必须以红色为例)
2019/11/20 Python
python用pip install时安装失败的一系列问题及解决方法
2020/02/24 Python
利用pandas向一个csv文件追加写入数据的实现示例
2020/04/23 Python
IE矩阵Matrix滤镜旋转与缩放及如何结合transform
2012/11/29 HTML / CSS
尼克松手表官网:Nixon手表
2019/03/17 全球购物
大学生活学习的自我评价
2013/12/03 职场文书
英文导游欢迎词
2014/01/11 职场文书
《中国的气候》教学反思
2014/02/23 职场文书
工作批评与自我批评范文
2014/10/16 职场文书
2015自愿离婚协议书范本
2015/01/28 职场文书
2015年全国爱耳日活动总结
2015/02/27 职场文书
婚宴主持词
2015/06/30 职场文书
党员学习中国梦心得体会
2016/01/05 职场文书
初一语文教学反思
2016/03/03 职场文书
php 防护xss,PHP的防御XSS注入的终极解决方案
2021/04/01 PHP
Python&Matlab实现灰狼优化算法的示例代码
2022/03/21 Python
macos系统如何实现微信双开? mac登录两个微信以上微信的技巧
2022/07/23 数码科技