to_mysql.py 1.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. import pandas as pd
  2. from sqlalchemy import create_engine
  3. from base_class import BaseVariableFunction
  4. from base_class import *
  5. baseclass = BaseVariableFunction(__file__)
  6. # 数据库连接信息
  7. username = 'root'
  8. password = '123456'
  9. # password = '123456abc'
  10. host = 'localhost'
  11. database = 'mine_01'
  12. table_name = 'table_01'
  13. # 创建数据库引擎
  14. engine = create_engine(f'mysql+pymysql://{username}:{password}@{host}/{database}')
  15. print("engine=",engine)
  16. con = engine.connect()#创建连接
  17. print(con)
  18. # 创建一个示例DataFrame
  19. # df = pd.DataFrame({
  20. # 'column1': [1, 2, 3],
  21. # 'column2': ['a', 'b', 'c']
  22. # })
  23. df = pd.read_excel(baseclass.library_path/f"a_case.xlsx",dtype =object)
  24. # df = pd.read_excel (f"a_case.xlsx",dtype =object)
  25. df = df.astype({
  26. "time":int,
  27. })
  28. print(df.head(5))
  29. # 将DataFrame写入MySQL表
  30. try:
  31. df.to_sql(name=table_name, con=con, if_exists='replace', index=False)
  32. print(f"DataFrame successfully written to table {table_name}")
  33. except Exception as e:
  34. print(f"An error occurred: {e}")