Python操作MySql数据库

Tags
#Python
./_image/Snip20161031_12.png

1.数据表

./_image/2016-10-31-23-01-22.png

2.实现代码

# coding:utf-8
# yutianran 2016/10/31 下午7:46

import sys
import os
import MySQLdb

reload(sys)
sys.setdefaultencoding("utf-8")

import MySQLdb

host = "127.0.0.1"
user = "root"
passwd = "123456"
port = "3306"
db = "test"

class TransferMoney(object):
    def __init__(self, conn):
        self.conn = conn

    def transfer(self, source_acctid, targt_acctid, money):
        try:
            self.check_acct_available(source_acctid)
            self.check_acct_available(targt_acctid)
            self.has_enough_money(source_acctid, money)
            self.reduce_money(source_acctid, money)
            self.add_money(targt_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)
            print "check_acct_available:" + 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

3.执行结果

./_image/2016-10-31-23-23-45.jpg

4.补充说明

代码其实很简单,主要就是引用了MySQLdb这个库,不过这个库配置的话有点蛋疼,我使用
后,最开始总是报:EnvironmentError: mysql_config not found。后来,我执行
然后就好了。不过,为了执行这个命令,因为我的Mac升级到了macOS Sierra,需要关闭SIP
其实这个过程中,还有一些坑,我就不一一细说了,大家不妨自己去亲自踩踩吧。
这个库有三大对象:
  1. conn:数据库连接对象
  1. cursor:数据库交互对象
  1. exptions:数据库异常类
./_image/Snip20161031_6.png
然后,连接数据库,执行CRUD操作
连接时的参数说明:
./_image/Snip20161031_7.png
./_image/Snip20161031_9.png
在本实例中,使用MySQLdb默认开启事务,执行转账事务的一系列操作,中间有错误就回滚。
./_image/Snip20161031_10.png

参考目录

  1. Python操作MySQL数据库
  1. MySQLdb在 OS X 中安装指南
  1. 如何关闭OSX 10.11 SIP

© fishyer 2022 - 2023