连接数据库操作
mysql主机:
1. 创建一个可以远程登陆的用户;
2. 给这个用户授权, 可以对哪个数据库操作;
3. 看防火墙是否管理;
python3主机:
1. 测试是否可以成功连接mysql主机?
2. 修改pycharm的解释器(安装pymysql模块)位置, 编写mysql代码,
如何自动提交对数据库的操作:
1.
2. 创建连接时,就指定:
pymysql.connect(host='192.168.122.170', user='hello',
password='hello', charset='utf8', autocommit=True)
import pymysql
conn = pymysql.connect(user='root',
password='971203', charset='utf8', autocommit=True)
cur = conn.cursor()
conn.select_db('westos')
try:
select_sqli = 'select * from myuser;'
res = cur.execute(select_sqli)
print("查找一条记录:", cur.fetchone())
print("查找一条记录:", cur.fetchone())
print("查找一条记录:", cur.fetchone())
print("查找一条记录:", cur.fetchone())
print("查找5条记录:",cur.fetchmany(5))
print("查找1所有记录", cur.fetchall())
cur.scroll(-10, mode='relative')
print("查找2所有记录", cur.fetchall())
except Exception as e:
print("Fail:", e)
else:
print("Success")
cur.close()
conn.close()
获取表的字段和信息
import pymysql
conn = pymysql.connect(host='192.168.122.170', user='hello',
password='hello', charset='utf8', autocommit=True,
db='westos')
with conn:
print("is_open", conn.open)
cur = conn.cursor()
res = cur.execute('select * from myuser;')
desc = cur.description
print("表的描述:",desc )
print("表头", ",".join([item[0] for item in desc]))
cur.close()
银行转账操作
import pymysql
class TransferMoney(object):
def __init__(self, conn):
self.conn = conn
self.cursor = conn.cursor()
def transfer(self, source_accid, target_accid, money):
"""
转账方法:
# 1. source_accid帐号是否存在;
# 2. target_accid帐号是否存在;
# 3. 是否有足够的钱
# 4. source_accid扣钱
# 5. target_acci加钱
# 6. 提交对数据库的操作
:param source_accid: 源帐号id
:param target_accid: 目标帐号id
:param money: 转账金额
:return: bool
"""
self.check_account_avaiable(source_accid)
self.check_account_avaiable(target_accid)
self.has_enough_money(source_accid, money)
try:
self.reduce_money(source_accid, money)
print(a)
self.add_money(target_accid, money)
self.conn.commit()
except Exception as e:
self.conn.rollback()
else:
print("%s给%s转账%s成功" %(source_accid, target_accid, money))
def check_account_avaiable(self, accid):
"""判断帐号是否存在, 传递参数为帐号id"""
select_sqli = 'select * from bankData where id=%s' %(accid)
print("execute sql:", select_sqli)
res = self.cursor.execute(select_sqli)
if res == 1:
return True
else:
raise Exception("帐号%s不存在" %(accid))
def has_enough_money(self, accid, money):
"""是否有足够的钱"""
select_sqli = 'select money from bankData where id=%s' %(accid)
print('execute sql:', select_sqli)
self.cursor.execute(select_sqli)
acc_money = self.cursor.fetchone()[0]
print(acc_money, type(acc_money))
if acc_money >= money:
return True
else:
raise Exception("账户%s没有足够的金额, 当前余额为%s" %(accid, acc_money))
def reduce_money(self, accid, money):
try:
update_sqli = 'update bankData set money=money-%s where id="%s"' %(money, accid)
print("redcue_money sql:", update_sqli)
self.cursor.execute(update_sqli)
except Exception as e:
print('Error:',e)
def add_money(self, accid, money):
try:
update_sqli = 'update bankData set money=money+%s where id="%s"' %(money, accid)
print("add_money sql:", update_sqli)
self.cursor.execute(update_sqli)
except Exception as e:
print('Error:',e)
def __del__(self):
self.cursor.close()
if __name__ == '__main__':
conn = pymysql.connect(user='root',
password='971203', charset='utf8',
db='westos')
trans = TransferMoney(conn)
try:
assert trans.check_account_avaiable('610001') == True
except AssertionError as e:
print(e)
else:
print("测试用例全部通过.....")
trans.has_enough_money('610001', 1000)
trans.has_enough_money('610001', 1001)
trans.reduce_money('610001', 200)
trans.add_money('610001', 200)
trans.transfer('610003', '610002', 100)
def create_data():
conn = pymysql.connect(user='root',
password='971203', charset='utf8',
autocommit=True, db='westos')
cur = conn.cursor()
try:
create_sqli = 'create table bankData( id int PRIMARY KEY, ' \
'name varchar(10), money FLOAT);'
cur.execute(create_sqli)
except Exception as e:
print("Error: 表已经创建", e)
else:
print("表创建成功")
a = 'set names latin1;'
cur.execute(a)
try:
users = [(610001, '张三', 1000), (610002, '李四', 1000),(610003, '粉条', 1000)]
insert_sqli = 'insert into bankData VALUES (%s, %s, %s);'
cur.executemany(insert_sqli, users)
except Exception as e:
print('Error:', e)
else:
print("初始化数据成功!")
cur.close()
conn.close()