2022年 11月 5日

python连接mysql(简单代码)

前言:

本文介绍两种写python连接mysql代码的方案:

1、线性代码

2、在框架中做配置模块+进行数据驱动

在操作之前需要先在数据库中,建一个mysql的表

一、python连接mysql线性代码

  1. # -*- coding: utf-8 -*-
  2. # @Author : hxy
  3. # @Time : 2022/1/10 10:51
  4. # @Function:
  5. '''
  6. 数据容器:mysql
  7. 操作数据库的步骤
  8. 1、连接数据库,通过connnect函数链接,生成connection对象
  9. 2、定义我们的游标Cursor,再通过我们游标执行脚本并获取结果
  10. 3、关闭连接
  11. '''
  12. import datetime
  13. import time
  14. import pymysql
  15. # 1、建立mysql连接
  16. conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', password='root', database='test_cases', charset='utf8')
  17. '''
  18. 常用方法:
  19. 1、cursor()使用当前连接创建并返回游标
  20. 2、commit()提交当前事务
  21. 3、rollback()回滚当前事务
  22. 4、close()关闭当前连接
  23. '''
  24. # 2、建立游标
  25. cur = conn.cursor()
  26. '''
  27. 游标操作方法:
  28. 1、execute()执行数据库查询或命令,将结果从数据库返回给客户端
  29. 2、fetchone()获取结果集的下一行
  30. 3、fetchall()获取结果集的所有行
  31. 4、fetchmany()获取结果集的几行
  32. '''
  33. now = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
  34. # now=datetime.datetime.now(.strftime("%Y-%m-%d %H:%M:%S"))
  35. # 3、执行脚本
  36. cur.execute('select weaid,success from weather')
  37. print(cur.fetchall())
  38. cur.execute('insert into weather(weaid,success,cre_time) values ("2","2","%s")' % now)
  39. cur.execute('commit')
  40. conn.close()

二、python连接mysql工具类+进行数据驱动+配置模块

即:将python连接mysql相关的代码封装起来,形成一个工具类,在需要使用的时候调用

准备工作:1、key_demo——2、cases|tool——3、cases/case.py|tool/MyDB.py

1、MyDB.py工具类

  1. # -*- coding: utf-8 -*-
  2. # @Author : hxy
  3. # @Time : 2022/1/18 15:20
  4. # @Function:
  5. import pymysql
  6. class my_db:
  7. '''
  8. 动作类:获取数据连接,连接ip,端口,账号密码。。
  9. '''
  10. # 构造函数
  11. def __init__(self):
  12. try:
  13. self.dbconn = pymysql.connect(host='127.0.0.1', port=3306, user='root', password='root',
  14. database='test_cases', charset='utf8')
  15. except Exception as e:
  16. print('初始化数据库连接失败:%s' % e)
  17. def close(self):
  18. self.dbconn.close()
  19. # query=查询语句
  20. def select_record(self, query):
  21. # 查询数据
  22. print('query:%s' % query)
  23. try:
  24. # 建立游标
  25. db_cursor = self.dbconn.cursor()
  26. db_cursor.execute(query)
  27. result = db_cursor.fetchall()
  28. return result
  29. except Exception as e:
  30. print('数据库查询数据失败:%s' % e)
  31. db_cursor.close()
  32. exit()
  33. # 插入
  34. def execute_insert(self, query):
  35. print('query:%s' % query)
  36. try:
  37. # 建立游标
  38. db_cursor = self.dbconn.cursor()
  39. db_cursor.execute(query)
  40. db_cursor.execute('commit')
  41. return True
  42. except Exception as e:
  43. print('数据库插入数据失败:%s' % e)
  44. # 事务回滚
  45. db_cursor.execute('rollback')
  46. db_cursor.close()
  47. exit()

2、case.py数据驱动

  1. # -*- coding: utf-8 -*-
  2. # @Author : hxy
  3. # @Time : 2022/1/7 15:07
  4. # @Function:
  5. # 针对数据库中的数据做数据驱动
  6. import time
  7. import unittest
  8. from ddt import ddt, data, unpack
  9. from key_demo.tool.MyDB import my_db
  10. # 必须要实例化,不然会报TypeError: select_record() missing 1 required positional argument: 'query'
  11. testdb = my_db()
  12. now = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
  13. @ddt
  14. class case(unittest.TestCase):
  15. # @data(*my_db().select_record('select weaid,success from weather'))
  16. @data(*testdb.select_record('select weaid,success from weather'))
  17. @unpack
  18. def test_1(self, weaid, success):
  19. print(weaid, success)
  20. testdb.execute_insert('insert into weather(weaid,success,cre_time) values ("2","2","%s")' % now)
  21. if __name__ == '__main__':
  22. unittest.main()

运行结果:

这样写的插入语句会被调用多次,要注意@data中执行的操作具体执行次数

换了一个写法,先插入,再查询

  1. # -*- coding: utf-8 -*-
  2. # @Author : hxy
  3. # @Time : 2022/1/7 15:07
  4. # @Function:
  5. # 针对数据库中的数据做数据驱动
  6. import time
  7. import unittest
  8. from ddt import ddt, data, unpack
  9. from key_demo.tool.MyDB import my_db
  10. # 必须要实例化,不然会报TypeError: select_record() missing 1 required positional argument: 'query'
  11. testdb = my_db()
  12. now = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
  13. @ddt
  14. class case(unittest.TestCase):
  15. # @data(*my_db().select_record('select weaid,success from weather'))
  16. @data(testdb.execute_insert('insert into weather(weaid,success,cre_time)values("2","2","%s")' % now))
  17. # @unpack
  18. def test_1(self,t):
  19. print(t)
  20. res = testdb.select_record('select weaid,success from weather')
  21. print(res)
  22. if __name__ == '__main__':
  23. unittest.main()

代码编写的时候有几个注意事项:

1、只执行一条语句,返回结果也只有一个,不需要@unpack解析

2、MyDB.py中定义有返回值,还有ddt中定义的语法return func(self, *args, **kwargs),不能缺少参数

运行结果: 

还有一种方式:

  1. @ddt
  2. class testcase(unittest.TestCase):
  3. @data(['2', '2'], ['1', '1'])
  4. @unpack
  5. def test_1(self, value1, value2):
  6. testdb.execute_insert('insert into weather(weaid,success,cre_time)values(' + value1 + ',' + value2 + ',%s)' % now)
  7. res = testdb.select_record('select weaid,success from weather')
  8. print(res)

可优化的点:data里面的值可以进行数据驱动测试,将数据和代码分离

数据放在yaml或者csv中读取

3、通过配置模块优化数据库连接

3、1定义配置项dbconfig.conf

1.key_demo——2.key_demo/config——3、key_demo/config/dbconfig.conf

  1. #测试环境
  2. [TESTDB]
  3. host=127.0.0.1
  4. port=3306
  5. user=root
  6. password=root
  7. db=test_cases
  8. charset=utf8
  9. [DEVDB]
  10. host=192.168.1.2
  11. port=3306
  12. user=root
  13. password=root
  14. db=test_cases1
  15. charset=utf8
  16. #生产环境
  17. [prdDB]
  18. host=192.168.1.4
  19. port=3306
  20. user=root
  21. password=root
  22. db=test_cases2
  23. charset=utf8

3、2改造工具类的构造函数

  1. # -*- coding: utf-8 -*-
  2. # @Author : hxy
  3. # @Time : 2022/1/18 15:20
  4. # @Function:
  5. import pymysql
  6. import configparser
  7. class my_db:
  8. '''
  9. 动作类:获取数据连接,连接ip,端口,账号密码。。
  10. '''
  11. # 构造函数
  12. def __init__(self, config_file, db):
  13. # 实例化configparser
  14. config = configparser.ConfigParser()
  15. # 从配置文件中读取数据库相关信息
  16. config.read(config_file)
  17. host = config[db]['host']
  18. port = int(config[db]['port'])
  19. user = config[db]['user']
  20. password = config[db]['password']
  21. database = config[db]['database']
  22. charset = config[db]['charset']
  23. try:
  24. self.dbconn = pymysql.connect(host, port, user, password, database, charset)
  25. except Exception as e:
  26. print('初始化数据库连接失败:%s' % e)
  27. def close(self):
  28. self.dbconn.close()
  29. # query=查询语句
  30. def select_record(self, query):
  31. # 查询数据
  32. print('query:%s' % query)
  33. try:
  34. # 建立游标
  35. db_cursor = self.dbconn.cursor()
  36. db_cursor.execute(query)
  37. result = db_cursor.fetchall()
  38. return result
  39. except Exception as e:
  40. print('数据库查询数据失败:%s' % e)
  41. db_cursor.close()
  42. exit()
  43. # 插入
  44. def execute_insert(self, query):
  45. print('query:%s' % query)
  46. try:
  47. # 建立游标
  48. db_cursor = self.dbconn.cursor()
  49. db_cursor.execute(query)
  50. db_cursor.execute('commit')
  51. return True
  52. except Exception as e:
  53. print('数据库插入数据失败:%s' % e)
  54. # 事务回滚
  55. db_cursor.execute('rollback')
  56. db_cursor.close()
  57. exit()

注意事项:configparser配置对象的使用

3、3在用例中的使用

  1. # -*- coding: utf-8 -*-
  2. # @Author : hxy
  3. # @Time : 2022/1/7 15:07
  4. # @Function:
  5. # 针对数据库中的数据做数据驱动
  6. import time
  7. import unittest
  8. from ddt import ddt, data, unpack
  9. from key_demo.tool.MyDB import my_db
  10. # 必须要实例化,不然会报TypeError: select_record() missing 1 required positional argument: 'query'
  11. # testdb = my_db('key_demo/config/dbconfig.conf','TESTDB')
  12. config_file='key_demo/config/dbconfig.conf'
  13. db='TESTDB'
  14. testdb=my_db(config_file,db)
  15. now = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
  16. @ddt
  17. class case(unittest.TestCase):
  18. # @data(*my_db().select_record('select weaid,success from weather'))
  19. @data(testdb.execute_insert('insert into weather(weaid,success,cre_time)values("2","2","%s")' % now))
  20. # @unpack
  21. def test_1(self, t):
  22. print(t)
  23. res = testdb.select_record('select weaid,success from weather')
  24. print(res)
  25. if __name__ == '__main__':
  26. unittest.main()

3、4运行结果