migrate_sqlite_to_mysql.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346
  1. """
  2. SQLite数据迁移到MySQL脚本
  3. 将SQLite数据库中的所有数据导出并导入到MySQL数据库
  4. """
  5. import sqlite3
  6. import sys
  7. import os
  8. from datetime import datetime
  9. # 尝试导入MySQL相关模块
  10. try:
  11. import pymysql
  12. PYMySQL_AVAILABLE = True
  13. except ImportError:
  14. PYMySQL_AVAILABLE = False
  15. print("错误: 请先安装pymysql: pip install pymysql")
  16. sys.exit(1)
  17. # 尝试导入配置模块
  18. try:
  19. import config
  20. MYSQL_CONFIG = getattr(config, 'MYSQL_CONFIG', {})
  21. except ImportError:
  22. print("错误: 找不到config.py配置文件")
  23. sys.exit(1)
  24. def get_base_path():
  25. """获取程序运行的基础路径"""
  26. if getattr(sys, 'frozen', False):
  27. return os.path.dirname(sys.executable)
  28. else:
  29. return os.path.dirname(os.path.abspath(__file__))
  30. def get_sqlite_db_path():
  31. """获取SQLite数据库路径"""
  32. base_path = get_base_path()
  33. return os.path.join(base_path, "dibang.db")
  34. def connect_mysql():
  35. """连接MySQL数据库"""
  36. try:
  37. conn = pymysql.connect(
  38. host=MYSQL_CONFIG.get('host', 'localhost'),
  39. port=MYSQL_CONFIG.get('port', 3306),
  40. user=MYSQL_CONFIG.get('user', 'root'),
  41. password=MYSQL_CONFIG.get('password', ''),
  42. database=MYSQL_CONFIG.get('database', 'dibang'),
  43. charset=MYSQL_CONFIG.get('charset', 'utf8mb4')
  44. )
  45. return conn
  46. except Exception as e:
  47. print(f"MySQL连接失败: {str(e)}")
  48. return None
  49. def export_data_to_sql_file(sqlite_path, output_file='sqlite_export.sql'):
  50. """
  51. 导出SQLite数据到SQL文件
  52. 生成可以直接在MySQL中执行的INSERT语句
  53. """
  54. if not os.path.exists(sqlite_path):
  55. print(f"错误: SQLite数据库文件不存在: {sqlite_path}")
  56. return False
  57. conn_sqlite = sqlite3.connect(sqlite_path)
  58. conn_sqlite.row_factory = sqlite3.Row
  59. cursor_sqlite = conn_sqlite.cursor()
  60. with open(output_file, 'w', encoding='utf-8') as f:
  61. f.write("-- SQLite数据导出到MySQL\n")
  62. f.write(f"-- 导出时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n\n")
  63. f.write("-- 禁用外键检查(如果需要)\n")
  64. f.write("SET FOREIGN_KEY_CHECKS = 0;\n\n")
  65. f.write("-- 清空表数据(可选,谨慎使用)\n")
  66. f.write("-- TRUNCATE TABLE companies;\n")
  67. f.write("-- TRUNCATE TABLE cargos;\n")
  68. f.write("-- TRUNCATE TABLE purchase_plans;\n")
  69. f.write("-- TRUNCATE TABLE weighing_slips;\n\n")
  70. # 导出公司表
  71. print("正在导出公司表数据...")
  72. cursor_sqlite.execute("SELECT * FROM companies ORDER BY id")
  73. companies = cursor_sqlite.fetchall()
  74. f.write("-- 公司表数据\n")
  75. for row in companies:
  76. name = str(row['name']).replace("'", "\\'").replace("\\", "\\\\")
  77. created_at = str(row['created_at'])
  78. f.write(f"INSERT INTO companies (name, created_at) VALUES ('{name}', '{created_at}');\n")
  79. f.write(f"-- 共 {len(companies)} 条公司记录\n\n")
  80. print(f" 导出了 {len(companies)} 条公司记录")
  81. # 导出货物表
  82. print("正在导出货物表数据...")
  83. cursor_sqlite.execute("SELECT * FROM cargos ORDER BY id")
  84. cargos = cursor_sqlite.fetchall()
  85. f.write("-- 货物表数据\n")
  86. for row in cargos:
  87. name = str(row['name']).replace("'", "\\'").replace("\\", "\\\\")
  88. created_at = str(row['created_at'])
  89. f.write(f"INSERT INTO cargos (name, created_at) VALUES ('{name}', '{created_at}');\n")
  90. f.write(f"-- 共 {len(cargos)} 条货物记录\n\n")
  91. print(f" 导出了 {len(cargos)} 条货物记录")
  92. # 导出采购计划表
  93. print("正在导出采购计划表数据...")
  94. cursor_sqlite.execute("SELECT * FROM purchase_plans ORDER BY id")
  95. plans = cursor_sqlite.fetchall()
  96. f.write("-- 采购计划表数据\n")
  97. for row in plans:
  98. plan_date = str(row['plan_date'])
  99. business_type = str(row['business_type']).replace("'", "\\'").replace("\\", "\\\\")
  100. product = str(row['product']).replace("'", "\\'").replace("\\", "\\\\")
  101. specification = str(row.get('specification', '') or '').replace("'", "\\'").replace("\\", "\\\\")
  102. planned_quantity = row['planned_quantity']
  103. vehicle_no = str(row['vehicle_no']).replace("'", "\\'").replace("\\", "\\\\")
  104. customer_name = str(row.get('customer_name', '') or '').replace("'", "\\'").replace("\\", "\\\\")
  105. remarks = str(row.get('remarks', '') or '').replace("'", "\\'").replace("\\", "\\\\")
  106. created_at = str(row['created_at'])
  107. f.write(f"INSERT INTO purchase_plans (plan_date, business_type, product, specification, "
  108. f"planned_quantity, vehicle_no, customer_name, remarks, created_at) VALUES "
  109. f"('{plan_date}', '{business_type}', '{product}', '{specification}', "
  110. f"{planned_quantity}, '{vehicle_no}', '{customer_name}', '{remarks}', '{created_at}');\n")
  111. f.write(f"-- 共 {len(plans)} 条采购计划记录\n\n")
  112. print(f" 导出了 {len(plans)} 条采购计划记录")
  113. # 导出地磅单表
  114. print("正在导出地磅单表数据...")
  115. cursor_sqlite.execute("SELECT * FROM weighing_slips ORDER BY id")
  116. slips = cursor_sqlite.fetchall()
  117. f.write("-- 地磅单表数据\n")
  118. for row in slips:
  119. vehicle_no = str(row['vehicle_no']).replace("'", "\\'").replace("\\", "\\\\")
  120. plan_no = str(row.get('plan_no', '') or '').replace("'", "\\'").replace("\\", "\\\\")
  121. cargo_name = str(row['cargo_name']).replace("'", "\\'").replace("\\", "\\\\")
  122. business_type = str(row['business_type']).replace("'", "\\'").replace("\\", "\\\\")
  123. batch_no = str(row.get('batch_no', '') or '').replace("'", "\\'").replace("\\", "\\\\")
  124. supplier = str(row['supplier']).replace("'", "\\'").replace("\\", "\\\\")
  125. consignee = str(row['consignee']).replace("'", "\\'").replace("\\", "\\\\")
  126. gross_weight = row['gross_weight']
  127. gross_weight_time = str(row['gross_weight_time'])
  128. tare_weight = row['tare_weight']
  129. tare_weight_time = str(row['tare_weight_time'])
  130. deduction = row.get('deduction', 0) or 0
  131. net_weight = row['net_weight']
  132. planned_quantity = row.get('planned_quantity') if row.get('planned_quantity') is not None else 'NULL'
  133. executed_quantity = row.get('executed_quantity') if row.get('executed_quantity') is not None else 'NULL'
  134. weighing_point = str(row.get('weighing_point', '山峡地磅') or '山峡地磅').replace("'", "\\'").replace("\\", "\\\\")
  135. remarks = str(row.get('remarks', '') or '').replace("'", "\\'").replace("\\", "\\\\")
  136. is_voided = row.get('is_voided', 0) or 0
  137. created_at = str(row['created_at'])
  138. planned_qty = f"'{planned_quantity}'" if planned_quantity != 'NULL' else 'NULL'
  139. executed_qty = f"'{executed_quantity}'" if executed_quantity != 'NULL' else 'NULL'
  140. f.write(f"INSERT INTO weighing_slips (vehicle_no, plan_no, cargo_name, business_type, batch_no, "
  141. f"supplier, consignee, gross_weight, gross_weight_time, tare_weight, tare_weight_time, "
  142. f"deduction, net_weight, planned_quantity, executed_quantity, weighing_point, remarks, "
  143. f"is_voided, created_at) VALUES "
  144. f"('{vehicle_no}', '{plan_no}', '{cargo_name}', '{business_type}', '{batch_no}', "
  145. f"'{supplier}', '{consignee}', {gross_weight}, '{gross_weight_time}', {tare_weight}, "
  146. f"'{tare_weight_time}', {deduction}, {net_weight}, {planned_qty}, {executed_qty}, "
  147. f"'{weighing_point}', '{remarks}', {is_voided}, '{created_at}');\n")
  148. f.write(f"-- 共 {len(slips)} 条地磅单记录\n\n")
  149. print(f" 导出了 {len(slips)} 条地磅单记录")
  150. f.write("-- 启用外键检查\n")
  151. f.write("SET FOREIGN_KEY_CHECKS = 1;\n")
  152. conn_sqlite.close()
  153. print(f"\n数据已导出到文件: {output_file}")
  154. return True
  155. def migrate_data_directly(sqlite_path):
  156. """
  157. 直接将SQLite数据迁移到MySQL
  158. 注意:这会清空MySQL中的现有数据并重新导入
  159. """
  160. if not os.path.exists(sqlite_path):
  161. print(f"错误: SQLite数据库文件不存在: {sqlite_path}")
  162. return False
  163. # 连接MySQL
  164. conn_mysql = connect_mysql()
  165. if conn_mysql is None:
  166. return False
  167. # 连接SQLite
  168. conn_sqlite = sqlite3.connect(sqlite_path)
  169. conn_sqlite.row_factory = sqlite3.Row
  170. cursor_sqlite = conn_sqlite.cursor()
  171. cursor_mysql = conn_mysql.cursor()
  172. try:
  173. print("\n开始迁移数据到MySQL...")
  174. print("警告: 这将清空MySQL中的所有数据!")
  175. # 确认
  176. confirm = input("是否继续? (yes/no): ")
  177. if confirm.lower() != 'yes':
  178. print("已取消迁移")
  179. return False
  180. # 清空MySQL表(注意顺序,因为有外键依赖)
  181. print("\n正在清空MySQL表...")
  182. cursor_mysql.execute("SET FOREIGN_KEY_CHECKS = 0")
  183. cursor_mysql.execute("TRUNCATE TABLE weighing_slips")
  184. cursor_mysql.execute("TRUNCATE TABLE purchase_plans")
  185. cursor_mysql.execute("TRUNCATE TABLE companies")
  186. cursor_mysql.execute("TRUNCATE TABLE cargos")
  187. cursor_mysql.execute("SET FOREIGN_KEY_CHECKS = 1")
  188. conn_mysql.commit()
  189. print("MySQL表已清空")
  190. # 迁移公司表
  191. print("\n正在迁移公司表数据...")
  192. cursor_sqlite.execute("SELECT * FROM companies ORDER BY id")
  193. companies = cursor_sqlite.fetchall()
  194. for row in companies:
  195. cursor_mysql.execute(
  196. "INSERT INTO companies (name, created_at) VALUES (%s, %s)",
  197. (row['name'], row['created_at'])
  198. )
  199. conn_mysql.commit()
  200. print(f" 迁移了 {len(companies)} 条公司记录")
  201. # 迁移货物表
  202. print("正在迁移货物表数据...")
  203. cursor_sqlite.execute("SELECT * FROM cargos ORDER BY id")
  204. cargos = cursor_sqlite.fetchall()
  205. for row in cargos:
  206. cursor_mysql.execute(
  207. "INSERT INTO cargos (name, created_at) VALUES (%s, %s)",
  208. (row['name'], row['created_at'])
  209. )
  210. conn_mysql.commit()
  211. print(f" 迁移了 {len(cargos)} 条货物记录")
  212. # 迁移采购计划表
  213. print("正在迁移采购计划表数据...")
  214. cursor_sqlite.execute("SELECT * FROM purchase_plans ORDER BY id")
  215. plans = cursor_sqlite.fetchall()
  216. for row in plans:
  217. cursor_mysql.execute(
  218. """INSERT INTO purchase_plans (plan_date, business_type, product, specification,
  219. planned_quantity, vehicle_no, customer_name, remarks, created_at)
  220. VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s)""",
  221. (
  222. row['plan_date'], row['business_type'], row['product'],
  223. row.get('specification', '') or '', row['planned_quantity'],
  224. row['vehicle_no'], row.get('customer_name', '') or '',
  225. row.get('remarks', '') or '', row['created_at']
  226. )
  227. )
  228. conn_mysql.commit()
  229. print(f" 迁移了 {len(plans)} 条采购计划记录")
  230. # 迁移地磅单表
  231. print("正在迁移地磅单表数据...")
  232. cursor_sqlite.execute("SELECT * FROM weighing_slips ORDER BY id")
  233. slips = cursor_sqlite.fetchall()
  234. for row in slips:
  235. cursor_mysql.execute(
  236. """INSERT INTO weighing_slips (vehicle_no, plan_no, cargo_name, business_type, batch_no,
  237. supplier, consignee, gross_weight, gross_weight_time, tare_weight, tare_weight_time,
  238. deduction, net_weight, planned_quantity, executed_quantity, weighing_point, remarks,
  239. is_voided, created_at) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)""",
  240. (
  241. row['vehicle_no'], row.get('plan_no', '') or '', row['cargo_name'],
  242. row['business_type'], row.get('batch_no', '') or '', row['supplier'],
  243. row['consignee'], row['gross_weight'], row['gross_weight_time'],
  244. row['tare_weight'], row['tare_weight_time'], row.get('deduction', 0) or 0,
  245. row['net_weight'], row.get('planned_quantity'), row.get('executed_quantity'),
  246. row.get('weighing_point', '山峡地磅') or '山峡地磅',
  247. row.get('remarks', '') or '', row.get('is_voided', 0) or 0,
  248. row['created_at']
  249. )
  250. )
  251. conn_mysql.commit()
  252. print(f" 迁移了 {len(slips)} 条地磅单记录")
  253. print("\n✅ 数据迁移完成!")
  254. print(f" 公司: {len(companies)} 条")
  255. print(f" 货物: {len(cargos)} 条")
  256. print(f" 采购计划: {len(plans)} 条")
  257. print(f" 地磅单: {len(slips)} 条")
  258. conn_sqlite.close()
  259. conn_mysql.close()
  260. return True
  261. except Exception as e:
  262. print(f"\n❌ 迁移失败: {str(e)}")
  263. conn_mysql.rollback()
  264. conn_sqlite.close()
  265. conn_mysql.close()
  266. return False
  267. def main():
  268. """主函数"""
  269. sqlite_path = get_sqlite_db_path()
  270. print("=" * 60)
  271. print("SQLite数据迁移到MySQL工具")
  272. print("=" * 60)
  273. print(f"SQLite数据库: {sqlite_path}")
  274. print(f"MySQL数据库: {MYSQL_CONFIG.get('host')}:{MYSQL_CONFIG.get('port')}/{MYSQL_CONFIG.get('database')}")
  275. print("=" * 60)
  276. print("\n请选择操作:")
  277. print("1. 导出SQLite数据为SQL文件(推荐,可手动检查后再导入)")
  278. print("2. 直接将SQLite数据迁移到MySQL(会清空MySQL现有数据)")
  279. print("3. 退出")
  280. choice = input("\n请输入选项 (1/2/3): ").strip()
  281. if choice == '1':
  282. output_file = input("\n请输入导出文件名(默认: sqlite_export.sql): ").strip()
  283. if not output_file:
  284. output_file = 'sqlite_export.sql'
  285. if export_data_to_sql_file(sqlite_path, output_file):
  286. print(f"\n✅ 导出成功!")
  287. print(f"你可以使用以下命令导入MySQL:")
  288. print(f" mysql -h {MYSQL_CONFIG.get('host')} -u {MYSQL_CONFIG.get('user')} -p {MYSQL_CONFIG.get('database')} < {output_file}")
  289. else:
  290. print("\n❌ 导出失败!")
  291. elif choice == '2':
  292. if migrate_data_directly(sqlite_path):
  293. print("\n迁移完成!")
  294. else:
  295. print("\n迁移失败!")
  296. elif choice == '3':
  297. print("已退出")
  298. else:
  299. print("无效选项")
  300. if __name__ == '__main__':
  301. main()