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操作Mysql实例代码教程在线版(查询手册)
Feb 18 Python
python实现解数独程序代码
Apr 12 Python
Python网络编程详解
Oct 31 Python
python 删除字符串中连续多个空格并保留一个的方法
Dec 22 Python
Python实现查找字符串数组最长公共前缀示例
Mar 27 Python
计算机二级python学习教程(2) python语言基本语法元素
May 16 Python
python使用 cx_Oracle 模块进行查询操作示例
Nov 28 Python
Python sklearn库实现PCA教程(以鸢尾花分类为例)
Feb 24 Python
Keras - GPU ID 和显存占用设定步骤
Jun 22 Python
如何在Win10系统使用Python3连接Hive
Oct 15 Python
python实现跨年表白神器--你值得拥有
Jan 04 Python
python邮件中附加文字、html、图片、附件实现方法
Jan 04 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
PHP5.0正式发布 不完全兼容PHP4 新增多项功能
2006/10/09 PHP
PHP处理SQL脚本文件导入到MySQL的代码实例
2014/03/17 PHP
yii用户注册表单验证实例
2015/12/26 PHP
php注册和登录界面的实现案例(推荐)
2016/10/24 PHP
ThinkPHP框架整合微信支付之JSAPI模式图文详解
2019/04/09 PHP
推荐40款强大的 jQuery 导航插件和教程(上篇)
2012/09/14 Javascript
使用jquery读取html5 localstorage的值的方法
2013/01/04 Javascript
js onclick事件传参讲解
2013/11/06 Javascript
如何减少浏览器的reflow和repaint
2015/02/26 Javascript
javascript实现Email邮件显示与删除功能
2015/11/21 Javascript
javascript创建对象、对象继承的实用方式详解
2016/03/08 Javascript
使用Bootstrap typeahead插件实现搜索框自动补全的方法
2016/07/07 Javascript
JS实现控制文本框的内容
2016/07/10 Javascript
JS中Object对象的原型概念基础
2018/01/29 Javascript
node.js学习笔记之koa框架和简单爬虫练习
2018/12/13 Javascript
js中async函数结合promise的小案例浅析
2019/04/14 Javascript
详解Angular cli配置过程记录
2019/11/07 Javascript
解决vue项目获取dom元素宽高总是不准确问题
2020/07/29 Javascript
解决vant title-active-color与title-inactive-color不生效问题
2020/11/03 Javascript
vue自定义组件实现双向绑定
2021/01/13 Vue.js
JavaScript/TypeScript 实现并发请求控制的示例代码
2021/01/18 Javascript
python文本数据相似度的度量
2018/03/12 Python
Python实现计算圆周率π的值到任意位的方法示例
2018/05/08 Python
Python爬虫信息输入及页面的切换方法
2018/05/11 Python
Python简单读写Xls格式文档的方法示例
2018/08/17 Python
python3+openCV 获取图片中文本区域的最小外接矩形实例
2020/06/02 Python
HTML5 window/iframe跨域传递消息 API介绍
2013/08/26 HTML / CSS
中学生期中自我鉴定
2014/04/20 职场文书
无刑事犯罪记录证明范本
2014/09/29 职场文书
汇报材料怎么写
2014/12/30 职场文书
2015年办公室文秘工作总结
2015/04/30 职场文书
撤诉书怎么写
2015/05/19 职场文书
复兴之路观后感3000字
2015/06/02 职场文书
公司联欢会主持词
2015/07/04 职场文书
高效笔记技巧分享:学会这些让你不再困扰
2019/09/04 职场文书
Kubernetes中Deployment的升级与回滚
2022/04/01 Servers