files.py 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171
  1. # -*- coding: utf-8 -*-
  2. import mysql.connector
  3. from mysql.connector import Error
  4. # 配置数据库连接
  5. DB_CONFIG = {
  6. 'host': '60.204.139.57',
  7. 'user': 'root',
  8. 'password': '1',
  9. 'port': 6003,
  10. 'database': 'files' # 替换为数据库名称
  11. }
  12. # 初始化数据库
  13. def initialize_files_database():
  14. try:
  15. # 连接 MySQL 服务器(不指定数据库)
  16. connection = mysql.connector.connect(
  17. host=DB_CONFIG['host'],
  18. user=DB_CONFIG['user'],
  19. password=DB_CONFIG['password'],
  20. port=DB_CONFIG['port']
  21. )
  22. if connection.is_connected():
  23. print("成功连接到 MySQL 服务器")
  24. cursor = connection.cursor()
  25. # 检查数据库是否存在
  26. cursor.execute(f"SHOW DATABASES LIKE '{DB_CONFIG['database']}';")
  27. result = cursor.fetchone()
  28. if result:
  29. print(f"数据库 {DB_CONFIG['database']} 已存在。")
  30. else:
  31. print(f"数据库 {DB_CONFIG['database']} 不存在,正在创建...")
  32. cursor.execute(f"CREATE DATABASE {DB_CONFIG['database']};")
  33. print(f"数据库 {DB_CONFIG['database']} 创建成功。")
  34. except Error as err:
  35. print(f"连接 MySQL 时发生错误:{err}")
  36. finally:
  37. if connection.is_connected():
  38. cursor.close()
  39. connection.close()
  40. print("MySQL 服务器连接已关闭")
  41. # 初始化表
  42. def initialize_files_table(table_name=None):
  43. if not table_name:
  44. table_name = 'filePath'
  45. # 验证表名是否合法(这里的规则可以根据你的需求做调整)
  46. allowed_tables = ['fruit', 'filePath'] # 你可以在这里列出允许的表名
  47. if table_name not in allowed_tables:
  48. raise ValueError(f"不允许使用此表名:{table_name}")
  49. try:
  50. connection = mysql.connector.connect(**DB_CONFIG)
  51. if connection.is_connected():
  52. cursor = connection.cursor()
  53. # 动态创建表
  54. create_table_query = f'''
  55. CREATE TABLE IF NOT EXISTS `{table_name}` (
  56. id INT AUTO_INCREMENT PRIMARY KEY,
  57. name VARCHAR(100)
  58. )
  59. '''
  60. cursor.execute(create_table_query)
  61. print(f"--- 创建 {table_name} 表 ---")
  62. except Error as err:
  63. print(f"初始化表时发生错误:{err}")
  64. finally:
  65. if connection.is_connected():
  66. cursor.close()
  67. connection.close()
  68. print("MySQL 连接已关闭")
  69. # 插入数据
  70. def insert_url(name):
  71. try:
  72. connection = mysql.connector.connect(**DB_CONFIG)
  73. if connection.is_connected():
  74. cursor = connection.cursor()
  75. # 插入数据
  76. cursor.execute("INSERT INTO filePath (name) VALUES (%s)", (name,))
  77. connection.commit()
  78. print(f"插入数据成功:({name})")
  79. except Error as err:
  80. print(f"插入数据时发生错误:{err}")
  81. finally:
  82. if connection.is_connected():
  83. cursor.close()
  84. connection.close()
  85. print("MySQL 连接已关闭")
  86. # 插入数据
  87. def insert_data(name, origin):
  88. try:
  89. connection = mysql.connector.connect(**DB_CONFIG)
  90. if connection.is_connected():
  91. cursor = connection.cursor()
  92. # 插入数据
  93. cursor.execute("INSERT INTO filePath (name, origin) VALUES (%s, %s)", (name, origin))
  94. connection.commit()
  95. print(f"插入数据成功:({name}, {origin})")
  96. except Error as err:
  97. print(f"插入数据时发生错误:{err}")
  98. finally:
  99. if connection.is_connected():
  100. cursor.close()
  101. connection.close()
  102. print("MySQL 连接已关闭")
  103. def delete_data(name):
  104. try:
  105. connection = mysql.connector.connect(**DB_CONFIG)
  106. if connection.is_connected():
  107. cursor = connection.cursor()
  108. # 删除数据
  109. cursor.execute("DELETE FROM filePath WHERE name = %s", (name,))
  110. connection.commit()
  111. print(f"成功删除名称为 {name} 的记录")
  112. except Error as err:
  113. print(f"删除数据时发生错误:{err}")
  114. finally:
  115. if connection.is_connected():
  116. cursor.close()
  117. connection.close()
  118. print("MySQL 连接已关闭")
  119. # 查询数据
  120. def fetch_data():
  121. try:
  122. connection = mysql.connector.connect(**DB_CONFIG)
  123. if connection.is_connected():
  124. cursor = connection.cursor()
  125. # 查询数据
  126. cursor.execute("SELECT * FROM filePath")
  127. rows = cursor.fetchall()
  128. print("--- 查询结果 ---")
  129. for row in rows:
  130. print(row)
  131. return rows
  132. except Error as err:
  133. print(f"查询数据时发生错误:{err}")
  134. finally:
  135. if connection.is_connected():
  136. cursor.close()
  137. connection.close()
  138. print("MySQL 连接已关闭")
  139. # 主函数
  140. if __name__ == "__main__":
  141. # 初始化数据库和表
  142. initialize_files_database()
  143. initialize_files_table()
  144. # 插入示例数据
  145. insert_data('Apple', 'China')
  146. insert_data('Banana', 'Ecuador')
  147. # 查询数据
  148. fetch_data()