test_mysql_conn.py 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. """
  4. MySQL连接工具类测试脚本
  5. """
  6. import sys
  7. import os
  8. # 添加项目根目录到Python路径
  9. sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
  10. from utils.mysql_conn import get_mysql_conn
  11. def test_mysql_conn():
  12. """
  13. 测试MySQL连接工具类
  14. """
  15. print("测试MySQL连接工具类...")
  16. try:
  17. # 获取MySQL连接管理器实例
  18. mysql_conn = get_mysql_conn(
  19. host="localhost",
  20. port=3306,
  21. user="root",
  22. password="password",
  23. database="test_db",
  24. pool_size=3
  25. )
  26. print("✓ 成功获取MySQL连接管理器实例")
  27. # 测试创建表
  28. create_table_sql = """
  29. CREATE TABLE IF NOT EXISTS test_users (
  30. id INT AUTO_INCREMENT PRIMARY KEY,
  31. name VARCHAR(50) NOT NULL,
  32. email VARCHAR(100) NOT NULL UNIQUE,
  33. created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
  34. ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
  35. """
  36. result = mysql_conn.execute(create_table_sql)
  37. print("✓ 成功创建测试表")
  38. # 测试插入数据
  39. insert_sql = "INSERT INTO test_users (name, email) VALUES (%s, %s)"
  40. insert_params = ("测试用户", "test@example.com")
  41. row_count = mysql_conn.execute(insert_sql, insert_params)
  42. print(f"✓ 成功插入 {row_count} 条数据")
  43. # 测试查询数据
  44. select_sql = "SELECT * FROM test_users WHERE name = %s"
  45. select_params = ("测试用户",)
  46. user = mysql_conn.fetch_one(select_sql, select_params)
  47. if user:
  48. print(f"✓ 成功查询数据: {user}")
  49. else:
  50. print("✗ 查询数据失败")
  51. # 测试批量插入
  52. bulk_insert_sql = "INSERT INTO test_users (name, email) VALUES (%s, %s)"
  53. bulk_params = [
  54. ("批量用户1", "batch1@example.com"),
  55. ("批量用户2", "batch2@example.com"),
  56. ("批量用户3", "batch3@example.com")
  57. ]
  58. bulk_row_count = mysql_conn.bulk_insert(bulk_insert_sql, bulk_params)
  59. print(f"✓ 成功批量插入 {bulk_row_count} 条数据")
  60. # 测试查询所有数据
  61. select_all_sql = "SELECT * FROM test_users"
  62. all_users = mysql_conn.fetch_all(select_all_sql)
  63. print(f"✓ 成功查询所有数据,共 {len(all_users)} 条")
  64. # 测试更新数据
  65. update_sql = "UPDATE test_users SET name = %s WHERE id = %s"
  66. update_params = ("更新后的测试用户", user["id"])
  67. update_row_count = mysql_conn.execute(update_sql, update_params)
  68. print(f"✓ 成功更新 {update_row_count} 条数据")
  69. # 测试删除数据
  70. delete_sql = "DELETE FROM test_users WHERE id = %s"
  71. delete_params = (user["id"],)
  72. delete_row_count = mysql_conn.execute(delete_sql, delete_params)
  73. print(f"✓ 成功删除 {delete_row_count} 条数据")
  74. # 测试事务
  75. print("测试事务处理...")
  76. conn, cursor = mysql_conn.begin_transaction()
  77. try:
  78. # 在事务中执行多个操作
  79. cursor.execute("INSERT INTO test_users (name, email) VALUES (%s, %s)", ("事务用户1", "transaction1@example.com"))
  80. cursor.execute("INSERT INTO test_users (name, email) VALUES (%s, %s)", ("事务用户2", "transaction2@example.com"))
  81. mysql_conn.commit_transaction(conn, cursor)
  82. print("✓ 事务提交成功")
  83. except Exception as e:
  84. mysql_conn.rollback_transaction(conn, cursor)
  85. print(f"✗ 事务回滚: {e}")
  86. # 清理测试数据
  87. drop_table_sql = "DROP TABLE IF EXISTS test_users"
  88. mysql_conn.execute(drop_table_sql)
  89. print("✓ 成功清理测试表")
  90. # 关闭连接池
  91. mysql_conn.close()
  92. print("✓ 成功关闭连接池")
  93. print("\n🎉 所有测试通过!MySQL连接工具类工作正常。")
  94. except Exception as e:
  95. print(f"\n❌ 测试失败: {e}")
  96. import traceback
  97. traceback.print_exc()
  98. return False
  99. return True
  100. if __name__ == "__main__":
  101. test_mysql_conn()