在操作之前,我们来看一下 python 是怎么连接 MySQL 数据库的。
首先我们需要下载必要的包 mysql-python,下载地址为:
https://sourceforge.net/projects/mysql-python/files/ 安装的过程不在赘述。
更多内容可以访问我的个人网站 http://www.cjluzzl.cn
安装完成后打开终端,进入 python 环境,输入 import MySQLdb 没有报错证明安装成功。
安装好必要的包我们来介绍一下连接数据库的原理。
首先打开数据库,创建一个 user_table 表
CREATE TABLE `user_table` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=utf8;
这里要注意设置存储引擎为 InnoDB,因为这个引擎支持事务。
然后随便添加几条数据。
然后开始测试
import MySQLdb
con = MySQLdb.connect(host='127.0.0.1',
port = 3306,
user = 'root',
passwd = '142857',
db = 'user',
charset='utf8')
cursor = con.cursor()
sql = 'select * from user_table'
cursor.execute(sql)
info = cursor.fetchall()
for i in info:
print i
print cursor.rowcount
cursor.close()
con.close()
运行结果如下
从运行结果可以看出,python是以元组的形式返回的数据库中的记录。执行完execute()影响的行数是9条。
总结一下连接数据库的步骤
参数名 |
类型 |
说明 |
host |
字符串 |
服务器地址 |
port |
数字 |
服务器端口号 |
user |
字符串 |
用户名 |
passwd |
字符串 |
密码 |
db |
字符串 |
数据库名称 |
charset |
字符串 |
连接编码 |
2. cursor = con.cursor()创建一个游标对象,用于查询和获取结果,cursor的方法有:
参数名 |
说明 |
execute(sql[,args]) |
执行一条SQL语句 |
fetchone() |
取结果集的下一行 |
fetchmany(size) |
取结果集的下几行 |
fetchall() |
获取结果集中剩下的所有行 |
rowcount |
最近一次执行execute返回的数据行数或影响行数 |
commit() |
提交事务 |
rollback() |
回滚事务,恢复数据到修改之前 |
close() |
关闭游标对象 |
测试增删改查操作
import MySQLdb
conn = MySQLdb.connect(
host = '127.0.0.1',
port = 3306,
user = 'root',
passwd = '142857',
db = 'user',
charset = 'utf8'
)
cursor = conn.cursor()
sql_insert = 'insert into user_table(`id`,`name`) values(10,"name10")'
sql_update = 'update user_table set `name`="name_07" where id =7'
sql_delete = "delete from user_table where id<3 "
try:
cursor.execute(sql_insert)
print cursor.rowcount
cursor.execute(sql_update)
print cursor.rowcount
cursor.execute(sql_delete)
print cursor.rowcount
conn.commit()
except Exception as e:
print e
conn.rollback()
cursor.close()
conn.close()
对比一下运行前后的数据库状态
运行前: 运行后:
这里特别要注意的是sql语句使用execute()方法执行后,要使用commit()方法提交处理,当事务失败后,要调用rollback()方法进行事务的回滚。注意尽量避免使用不支持事务的存储引擎。
使用python操作数据库模拟银行转账的功能
import sys
import MySQLdb
class TransferMoney():
def __init__(self,conn):
self.conn = conn
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, money):
cursor = self.conn.cursor()
try:
sql = 'update account set money=money+%s where acctid=%s' % (money,acctid)
cursor.execute(sql)
print 'add_money:' + sql
if cursor.rowcount != 1:
raise Exception("账号%s加款失败" % acctid)
finally:
cursor.close()
def transfer(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
if __name__ == "__main__":
source_acctid = sys.argv[1]
target_acctid = sys.argv[2]
money = sys.argv[3]
print source_acctid,' ',target_acctid,' ',money
conn = MySQLdb.connect(host='127.0.0.1',port = 3306,user = 'root',passwd='142857',db ='user',charset = 'utf8')
tr_money = TransferMoney(conn)
try:
tr_money.transfer(source_acctid,target_acctid,money)
except Exception as e:
print u'出现问题',e
finally:
conn.close()
账户 11 余额为110元
账户 12 余额为10元
执行12 11 100意为账户12转给账户11 100元,则转账失败
转账失败那么11的钱没增加,12的钱也不能少,回到数据的初始状态,这就是事务的回滚。
当账户11转给12账户100元时,可以完成操作,转账成功。回到数据库刷新可以看到11的钱少了100元,12的钱增加了100元。