copy_db.py 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. import pymysql
  2. from tqdm import tqdm
  3. # Remote database configuration
  4. remote_db_config = {
  5. 'host': '192.168.31.111',
  6. 'port': 3307,
  7. 'user': 'root',
  8. 'password': 'r6kEwqWU9!v3',
  9. 'database': 'qmt_stocks_whole'
  10. }
  11. # Local database configuration
  12. local_db_config = {
  13. 'host': 'localhost',
  14. 'port': 3307,
  15. 'user': 'root',
  16. 'password': 'r6kEwqWU9!v3',
  17. 'database': 'qmt_stocks_whole'
  18. }
  19. def fetch_tables(cursor):
  20. cursor.execute("SHOW TABLES")
  21. return [table[0] for table in cursor.fetchall()]
  22. def fetch_table_schema(cursor, table_name):
  23. cursor.execute(f"SHOW CREATE TABLE `{table_name}`")
  24. return cursor.fetchone()[1]
  25. def fetch_table_data(cursor, table_name):
  26. cursor.execute(f"SELECT * FROM `{table_name}`")
  27. return cursor.fetchall(), cursor.description
  28. def create_table(cursor, create_table_sql):
  29. cursor.execute(create_table_sql)
  30. def insert_data(cursor, table_name, data, description):
  31. columns = ", ".join([desc[0] for desc in description])
  32. placeholders = ", ".join(["%s"] * len(description))
  33. insert_sql = f"INSERT INTO `{table_name}` ({columns}) VALUES ({placeholders})"
  34. cursor.executemany(insert_sql, data)
  35. def drop_table_if_exists(cursor, table_name):
  36. cursor.execute(f"DROP TABLE IF EXISTS `{table_name}`")
  37. def table_exists(cursor, table_name):
  38. cursor.execute(f"SHOW TABLES LIKE '{table_name}'")
  39. return cursor.fetchone() is not None
  40. def main():
  41. # Connect to remote database
  42. remote_conn = pymysql.connect(**remote_db_config)
  43. remote_cursor = remote_conn.cursor()
  44. # Connect to local database
  45. local_conn = pymysql.connect(**local_db_config)
  46. local_cursor = local_conn.cursor()
  47. try:
  48. # Fetch all tables from remote database
  49. tables = fetch_tables(remote_cursor)
  50. for table in tqdm(tables, desc="Processing tables"):
  51. # Fetch table schema
  52. create_table_sql = fetch_table_schema(remote_cursor, table)
  53. # Check if table exists in local database
  54. if table_exists(local_cursor, table):
  55. # Drop table in local database if exists
  56. drop_table_if_exists(local_cursor, table)
  57. # Create table in local database
  58. create_table(local_cursor, create_table_sql)
  59. # Fetch table data
  60. data, description = fetch_table_data(remote_cursor, table)
  61. # Insert data into local database
  62. insert_data(local_cursor, table, data, description)
  63. local_conn.commit()
  64. finally:
  65. remote_cursor.close()
  66. remote_conn.close()
  67. local_cursor.close()
  68. local_conn.close()
  69. if __name__ == "__main__":
  70. main()