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库urllib与urllib2主要区别分析
Jul 13 Python
web.py获取上传文件名的正确方法
Aug 26 Python
利用Python的Django框架中的ORM建立查询API
Apr 20 Python
用Python程序抓取网页的HTML信息的一个小实例
May 02 Python
Django URL传递参数的方法总结
Aug 28 Python
详解Python中for循环是如何工作的
Jun 30 Python
对Python3使运行暂停的方法详解
Feb 18 Python
使用Python来做一个屏幕录制工具的操作代码
Jan 18 Python
Python批量启动多线程代码实例
Feb 18 Python
浅谈Python 中的复数问题
May 19 Python
python实现简易自习室座位预约系统
Jun 30 Python
Python制作表白爱心合集
Jan 22 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利用正则表达式解决采集内容排版的问题
2013/06/20 PHP
各种快递查询--Api接口
2016/04/26 PHP
thinkPHP订单数字提醒功能的实现方法
2016/12/01 PHP
php微信公众号开发(2)百度BAE搭建和数据库使用
2016/12/15 PHP
如何利用PHP实现上传图片功能详解
2020/09/24 PHP
js输出列表实现代码
2010/09/12 Javascript
基于jquery的has()方法以及与find()方法以及filter()方法的区别详解
2013/04/26 Javascript
javascript对话框使用方法(警告框 javascript确认框 提示框)
2014/01/07 Javascript
Juery解决tablesorter中文排序和字符范围的方法
2015/05/06 Javascript
JQUERY简单按钮轮换选中效果实现方法
2015/05/07 Javascript
JS中处理时间之setUTCMinutes()方法的使用
2015/06/12 Javascript
浅谈几种常用的JS类定义方法
2016/06/08 Javascript
jQuery文本框得到与失去焦点动态改变样式效果
2016/09/08 Javascript
详解JS-- 浮点数运算处理
2016/11/28 Javascript
关于Javascript中document.cookie的使用
2017/03/08 Javascript
JavaScript实现写入文件到本地的方法【基于FileSaver.js插件】
2018/03/15 Javascript
JavaScript实现的简单加密解密操作示例
2018/06/01 Javascript
angular2 组件之间通过service互相传递的实例
2018/09/30 Javascript
Python模块学习 filecmp 文件比较
2012/08/27 Python
python3读取MySQL-Front的MYSQL密码
2017/05/03 Python
Python实现多并发访问网站功能示例
2017/06/19 Python
python 协程 gevent原理与用法分析
2019/11/22 Python
乌克兰在线商店的价格比较:Price.ua
2019/07/26 全球购物
如何手工释放资源
2013/12/15 面试题
建筑文秘专业个人求职信范文
2013/12/28 职场文书
《槐乡五月》教学反思
2014/04/25 职场文书
小学雷锋月活动总结
2014/07/03 职场文书
单位工作证明范文
2014/09/14 职场文书
2014年团支书工作总结
2014/11/14 职场文书
金融专业银行实习证明模板
2014/11/28 职场文书
搞笑结婚保证书
2015/05/08 职场文书
防溺水主题班会教案
2015/08/12 职场文书
导游词之珠海轮廓
2019/10/25 职场文书
vue实现同时设置多个倒计时
2021/05/20 Vue.js
python中%格式表达式实例用法
2021/06/18 Python
Java Redisson多策略注解限流
2022/09/23 Java/Android