[数据库] python连接数据库

199 0
Honkers 2025-6-1 18:02:10 | 显示全部楼层 |阅读模式

一、python连接数据库
pyton连接数据库需要先安装pymysql模块:pip install pymysql
安装完成后导入pymysql模块:import pymysql
python连接数据库主要分五个步骤:
step1:连接数据库
step2:创建游标对象
step3:对数据库进行增删改查
step4:关闭游标
step5:关闭连接

  1. # 1. 连接数据库,
  2. conn = pymysql.connect(
  3. host='localhost',
  4. user='root',
  5. password='redhat',
  6. db='helloTest',
  7. charset='utf8',
  8. # autocommit=True, # 如果插入数据,, 是否自动提交? 和conn.commit()功能一致。
  9. )
  10. # ****python, 必须有一个游标对象, 用来给数据库发送sql语句, 并执行的.
  11. # 2. 创建游标对象,
  12. cur = conn.cursor()
  13. # 3. 对于数据库进行增删改查
  14. # 1). ************************创建数据表**********************************
  15. try:
  16. create_sqli = "create table hello (id int, name varchar(30));"
  17. cur.execute(create_sqli)
  18. except Exception as e:
  19. print("创建数据表失败:", e)
  20. else:
  21. print("创建数据表成功;")
  22. ## 2). *********************插入数据****************************
  23. try:
  24. insert_sqli = "insert into hello values(2, 'fensi');"
  25. cur.execute(insert_sqli)
  26. except Exception as e:
  27. print("插入数据失败:", e)
  28. else:
  29. # 如果是插入数据, 一定要提交数据, 不然数据库中找不到要插入的数据;
  30. conn.commit()
  31. print("插入数据成功;")
  32. # 3). *********************插入多条数据****************************
  33. try:
  34. info = [(i, "westos%s" %(i)) for i in range(100)]
  35. # *********************第一种方式********************
  36. # %s必须手动添加一个字符串, 否则就是一个变量名, 会报错.
  37. insert_sqli = "insert into hello values(%d, '%s');"
  38. for item in info:
  39. print('insert语句:', insert_sqli %item)
  40. cur.execute(insert_sqli %item)
  41. # *********************第二种方式********************
  42. insert_sqli = "insert into hello values(%s, %s);"
  43. cur.executemany(insert_sqli, info )
  44. except Exception as e:
  45. print("插入多条数据失败:", e)
  46. else:
  47. # 如果是插入数据, 一定要提交数据, 不然数据库中找不到要插入的数据;
  48. conn.commit()
  49. print("插入多条数据成功;")
  50. # 4). **************************数据库查询*****************************
  51. sqli = "select * from hello;"
  52. result = cur.execute(sqli) # 默认不返回查询结果集, 返回数据记录数。
  53. print(result)
  54. print(cur.fetchone()) # 1). 获取下一个查询结果集;
  55. print(cur.fetchone())
  56. print(cur.fetchone())
  57. print(cur.fetchmany(4)) # 2). 获取制定个数个查询结果集;
  58. info = cur.fetchall() # 3). 获取所有的查询结果
  59. print(info)
  60. print(len(info))
  61. print(cur.rowcount) # 4). 返回执行sql语句影响的行数
  62. # 5). 移动游标指针
  63. print(cur.fetchmany(3))
  64. print("正在移动指针到最开始......")
  65. cur.scroll(0, 'absolute')
  66. print(cur.fetchmany(3))
  67. print("正在移动指针到倒数第2个......")
  68. print(cur.fetchall()) # 移动到最后
  69. cur.scroll(-2, mode='relative')
  70. print(cur.fetchall())
  71. # 4. 关闭游标
  72. cur.close()
  73. # 5. 关闭连接
  74. conn.close()
复制代码

操作运行结果截图:
1.创建数据表:


2.插入数据;

3.插入多条数据(第一种方法);

3.插入多条数据(第二种方法)

4.数据库查询;

5.移动游标指针

二、获取表的字段名和信息
首先导入所需要的模块

  1. import time
  2. import pymysql
复制代码

然后进入主程序部分:此部分用with语句编写(with语句实现的效果是: with语句执行结束, 如果成功, 则提交改变的数据, 如果不成功, 则回滚.)

  1. conn = pymysql.connect(
  2. host='localhost',
  3. user='root',
  4. password='redhat',
  5. db='helloTest',
  6. charset='utf8',
  7. # autocommit=True, # 如果插入数据,, 是否自动提交? 和conn.commit()功能一致。
  8. ) #连接数据库
  9. with conn: #主程序with语句部分
  10. # ****** 判断是否连接?
  11. print(conn.open) # True
  12. # 2. 创建游标对象,
  13. cur = conn.cursor()
  14. # 3).
  15. sqli = "select * from hello;"
  16. result = cur.execute(sqli) # 默认不返回查询结果集, 返回数据记录数。
  17. # 显示每列的详细信息
  18. des = cur.description
  19. print("表的描述:", des)
  20. # 获取表头
  21. print("表头:", ",".join([item[0] for item in des]))
  22. cur.close() #关闭游标,with语句内部
  23. conn.close() #关闭指针,with语句外部
  24. print("with语句之外:", conn.open) # 正确情况下会是False
复制代码

操作运行结果;

三、基于mysql数据库银行转账功能实现
银行转账系统考虑因素主要包括:
1). 判断两个银行卡号是否存在?
2). 判断source_id是否有足够的钱?
3). source_id扣钱
4). target_id加钱
代码如下:

  1. import pymysql
  2. class TransferMoney(object):
  3. # 构造方法
  4. def __init__(self, conn):
  5. self.conn = conn
  6. self.cur = conn.cursor()
  7. def transfer(self, source_id, target_id, money):
  8. if not self.check_account_avaialbe(source_id):
  9. raise Exception("账户不存在")
  10. if not self.check_account_avaialbe(target_id):
  11. raise Exception("账户不存在")
  12. if self.has_enough_money(source_id, money):
  13. try:
  14. self.reduce_money(source_id, money)
  15. self.add_money(target_id, money)
  16. except Exception as e:
  17. print("转账失败:", e)
  18. self.conn.rollback()
  19. else:
  20. self.conn.commit()
  21. print("%s给%s转账%s金额成功" % (source_id, target_id, money))
  22. def check_account_avaialbe(self, acc_id):
  23. """判断帐号是否存在, 传递的参数是银行卡号的id"""
  24. select_sqli = "select * from bankData where id=%d;" % (acc_id)
  25. print("execute sql:", select_sqli)
  26. res_count = self.cur.execute(select_sqli)
  27. if res_count == 1:
  28. return True
  29. else:
  30. # raise Exception("账户%s不存在" %(acc_id))
  31. return False
  32. def has_enough_money(self, acc_id, money):
  33. """判断acc_id账户上金额> money"""
  34. # 查找acc_id存储金额?
  35. select_sqli = "select money from bankData where id=%d;" % (acc_id)
  36. print("execute sql:", select_sqli)
  37. self.cur.execute(select_sqli) # ((1, 500), )
  38. # 获取查询到的金额钱数;
  39. acc_money = self.cur.fetchone()[0]
  40. # 判断
  41. if acc_money >= money:
  42. return True
  43. else:
  44. return False
  45. def add_money(self, acc_id, money):
  46. update_sqli = "update bankData set money=money+%d where id=%d" % (money, acc_id)
  47. print("add money:", update_sqli)
  48. self.cur.execute(update_sqli)
  49. def reduce_money(self, acc_id, money):
  50. update_sqli = "update bankData set money=money-%d where id=%d" % (money, acc_id)
  51. print("reduce money:", update_sqli)
  52. self.cur.execute(update_sqli)
  53. # 析构方法
  54. def __del__(self):
  55. self.cur.close()
  56. self.conn.close()
  57. if __name__ == '__main__':
  58. # 1. 连接数据库,
  59. conn = pymysql.connect(
  60. host='localhost',
  61. user='root',
  62. password='redhat',
  63. db='helloTest',
  64. charset='utf8',
  65. autocommit=True, # 如果插入数据,, 是否自动提交? 和conn.commit()功能一致。
  66. )
  67. trans = TransferMoney(conn)
  68. trans.transfer(13997, 13998, 200) #账户13997向13998转账200
复制代码

测试时,首先在数据库中构造数据表bankData,在数据表中添加用户信息(包括用户帐号和账户内金额)
如下:


运行代码后数据库内金额发生变化,由账户13997向账户13998转账200元:

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

×
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

中国红客联盟公众号

联系站长QQ:5520533

admin@chnhonker.com
Copyright © 2001-2025 Discuz Team. Powered by Discuz! X3.5 ( 粤ICP备13060014号 )|天天打卡 本站已运行