MySQLdb
时间:2021-07-01 10:21:17
帮助过:28人阅读
Python DB API
# 数据库连接对象 connection
# cursor 使用该连接创建并返回游标
# commit 提交当前事务
# rollback 回滚当前事务
# close 关闭连接
# 数据库交互对象 cursor
# 游标对象 用于执行查询和获取结果
# execute(op[,args]) 执行一个数据库查询和命令
# fetchone() 获取结果集的下一行
# fetchmany(size) 获取结果集的下几行
# fetchall() 获取结果集中剩下的所有行
# rowcount 最近一次execute返回数据的行数或影响行数
# close() 关闭游标对象
# 安装
# Python-MySQL connector
# sourceforge.net/projects/mysql-python
# 事务
# 关闭自动commit conn.autocommit(False)
# 否则每条sql作为事务单独提交
# conn.commit()
# conn.rollback()
import MySQLdb
conn =
MySQLdb.Connect(
host =
‘127.0.0.1‘,
post = 3306
,
user =
‘root‘,
passwd =
‘123456‘,
db =
‘imooc‘,
charset =
‘utf8‘
)
def check_acct_available(acctid):
cursor =
conn.cursor()
try:
sql =
‘select * from account where acctid=%s‘ %
acctid
cursor.execute(sql)
cursor.rowcount
#cursor.fetchall()
#cursor.fetchmany(3)
rs =
cursor.fetchone()
if len(rs) != 1
:
raise Exception(
"账号%s不存在" %
acctid)
finally:
cursor.close()
def has_enough_money(acctid, money):
cursor =
conn.cursor()
try:
sql =
‘select * from account where acctid=%s and money>%s‘ %
(acctid, money)
cursor.execute(sql)
rs =
cursor.fetchone()
if len(rs) != 1
:
raise Exception(
"账号%s没有足够的钱" %
acctid)
finally:
cursor.close()
def reduce_money(acctid, money):
cursor =
conn.cursor()
try:
sql =
‘update account set money=money-%s where acctid=%s‘ %
(money, acctid)
cursor.execute(sql)
if cursor.rowcount != 1
:
raise Exception(
"账号%s减款失败" %
acctid)
finally:
cursor.close()
def add_money(acctid, money):
cursor =
conn.cursor()
try:
sql =
‘update account set money=money+%s where acctid=%s‘ %
(money, acctid)
cursor.execute(sql)
if cursor.rowcount != 1
:
raise Exception(
"账号%s加款失败" %
acctid)
finally:
cursor.close()
try:
check_acct_available(1
)
has_enough_money(1, 100
)
reduce_money(1, 100
)
add_money(2, 100
)
conn.commit()
except Exception as e:
conn.rollback()
finally:
conn.close()
MySQLdb
标签:rgs where final 数据库连接 src innodb except .com 连接