一、python连接数据库 pyton连接数据库需要先安装pymysql模块:pip install pymysql 安装完成后导入pymysql模块:import pymysql python连接数据库主要分五个步骤: step1:连接数据库 step2:创建游标对象 step3:对数据库进行增删改查 step4:关闭游标 step5:关闭连接 - # 1. 连接数据库,
- conn = pymysql.connect(
- host='localhost',
- user='root',
- password='redhat',
- db='helloTest',
- charset='utf8',
- # autocommit=True, # 如果插入数据,, 是否自动提交? 和conn.commit()功能一致。
- )
- # ****python, 必须有一个游标对象, 用来给数据库发送sql语句, 并执行的.
- # 2. 创建游标对象,
- cur = conn.cursor()
- # 3. 对于数据库进行增删改查
- # 1). ************************创建数据表**********************************
- try:
- create_sqli = "create table hello (id int, name varchar(30));"
- cur.execute(create_sqli)
- except Exception as e:
- print("创建数据表失败:", e)
- else:
- print("创建数据表成功;")
- ## 2). *********************插入数据****************************
- try:
- insert_sqli = "insert into hello values(2, 'fensi');"
- cur.execute(insert_sqli)
- except Exception as e:
- print("插入数据失败:", e)
- else:
- # 如果是插入数据, 一定要提交数据, 不然数据库中找不到要插入的数据;
- conn.commit()
- print("插入数据成功;")
- # 3). *********************插入多条数据****************************
- try:
- info = [(i, "westos%s" %(i)) for i in range(100)]
- # *********************第一种方式********************
- # %s必须手动添加一个字符串, 否则就是一个变量名, 会报错.
- insert_sqli = "insert into hello values(%d, '%s');"
- for item in info:
- print('insert语句:', insert_sqli %item)
- cur.execute(insert_sqli %item)
- # *********************第二种方式********************
- insert_sqli = "insert into hello values(%s, %s);"
- cur.executemany(insert_sqli, info )
- except Exception as e:
- print("插入多条数据失败:", e)
- else:
- # 如果是插入数据, 一定要提交数据, 不然数据库中找不到要插入的数据;
- conn.commit()
- print("插入多条数据成功;")
- # 4). **************************数据库查询*****************************
- sqli = "select * from hello;"
- result = cur.execute(sqli) # 默认不返回查询结果集, 返回数据记录数。
- print(result)
- print(cur.fetchone()) # 1). 获取下一个查询结果集;
- print(cur.fetchone())
- print(cur.fetchone())
- print(cur.fetchmany(4)) # 2). 获取制定个数个查询结果集;
- info = cur.fetchall() # 3). 获取所有的查询结果
- print(info)
- print(len(info))
- print(cur.rowcount) # 4). 返回执行sql语句影响的行数
- # 5). 移动游标指针
- print(cur.fetchmany(3))
- print("正在移动指针到最开始......")
- cur.scroll(0, 'absolute')
- print(cur.fetchmany(3))
- print("正在移动指针到倒数第2个......")
- print(cur.fetchall()) # 移动到最后
- cur.scroll(-2, mode='relative')
- print(cur.fetchall())
- # 4. 关闭游标
- cur.close()
- # 5. 关闭连接
- conn.close()
复制代码
操作运行结果截图: 1.创建数据表: 2.插入数据; 3.插入多条数据(第一种方法); 3.插入多条数据(第二种方法) 4.数据库查询; 5.移动游标指针 二、获取表的字段名和信息 首先导入所需要的模块 - import time
- import pymysql
复制代码
然后进入主程序部分:此部分用with语句编写(with语句实现的效果是: with语句执行结束, 如果成功, 则提交改变的数据, 如果不成功, 则回滚.) - conn = pymysql.connect(
- host='localhost',
- user='root',
- password='redhat',
- db='helloTest',
- charset='utf8',
- # autocommit=True, # 如果插入数据,, 是否自动提交? 和conn.commit()功能一致。
- ) #连接数据库
- with conn: #主程序with语句部分
- # ****** 判断是否连接?
- print(conn.open) # True
- # 2. 创建游标对象,
- cur = conn.cursor()
- # 3).
- sqli = "select * from hello;"
- result = cur.execute(sqli) # 默认不返回查询结果集, 返回数据记录数。
- # 显示每列的详细信息
- des = cur.description
- print("表的描述:", des)
- # 获取表头
- print("表头:", ",".join([item[0] for item in des]))
- cur.close() #关闭游标,with语句内部
- conn.close() #关闭指针,with语句外部
- print("with语句之外:", conn.open) # 正确情况下会是False
复制代码
操作运行结果;
三、基于mysql数据库银行转账功能实现 银行转账系统考虑因素主要包括: 1). 判断两个银行卡号是否存在? 2). 判断source_id是否有足够的钱? 3). source_id扣钱 4). target_id加钱 代码如下: - import pymysql
- class TransferMoney(object):
- # 构造方法
- def __init__(self, conn):
- self.conn = conn
- self.cur = conn.cursor()
- def transfer(self, source_id, target_id, money):
- if not self.check_account_avaialbe(source_id):
- raise Exception("账户不存在")
- if not self.check_account_avaialbe(target_id):
- raise Exception("账户不存在")
- if self.has_enough_money(source_id, money):
- try:
- self.reduce_money(source_id, money)
- self.add_money(target_id, money)
- except Exception as e:
- print("转账失败:", e)
- self.conn.rollback()
- else:
- self.conn.commit()
- print("%s给%s转账%s金额成功" % (source_id, target_id, money))
-
- def check_account_avaialbe(self, acc_id):
- """判断帐号是否存在, 传递的参数是银行卡号的id"""
- select_sqli = "select * from bankData where id=%d;" % (acc_id)
- print("execute sql:", select_sqli)
- res_count = self.cur.execute(select_sqli)
- if res_count == 1:
- return True
- else:
- # raise Exception("账户%s不存在" %(acc_id))
- return False
-
- def has_enough_money(self, acc_id, money):
- """判断acc_id账户上金额> money"""
- # 查找acc_id存储金额?
- select_sqli = "select money from bankData where id=%d;" % (acc_id)
- print("execute sql:", select_sqli)
- self.cur.execute(select_sqli) # ((1, 500), )
- # 获取查询到的金额钱数;
- acc_money = self.cur.fetchone()[0]
- # 判断
- if acc_money >= money:
- return True
- else:
- return False
- def add_money(self, acc_id, money):
- update_sqli = "update bankData set money=money+%d where id=%d" % (money, acc_id)
- print("add money:", update_sqli)
- self.cur.execute(update_sqli)
- def reduce_money(self, acc_id, money):
- update_sqli = "update bankData set money=money-%d where id=%d" % (money, acc_id)
- print("reduce money:", update_sqli)
- self.cur.execute(update_sqli)
- # 析构方法
- def __del__(self):
- self.cur.close()
- self.conn.close()
-
- if __name__ == '__main__':
- # 1. 连接数据库,
- conn = pymysql.connect(
- host='localhost',
- user='root',
- password='redhat',
- db='helloTest',
- charset='utf8',
- autocommit=True, # 如果插入数据,, 是否自动提交? 和conn.commit()功能一致。
- )
- trans = TransferMoney(conn)
- trans.transfer(13997, 13998, 200) #账户13997向13998转账200
复制代码
测试时,首先在数据库中构造数据表bankData,在数据表中添加用户信息(包括用户帐号和账户内金额) 如下: 运行代码后数据库内金额发生变化,由账户13997向账户13998转账200元: |