sql_query.py 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. import pandas as pd
  2. from sqlalchemy import create_engine
  3. from database import conn_string
  4. cfg = {
  5. "clients": [
  6. "deop01",
  7. "deop02",
  8. "deop03",
  9. "deop04",
  10. "deop05",
  11. "deop06",
  12. "deop07",
  13. "deop08",
  14. "deop09",
  15. "deop10",
  16. "deop11",
  17. "deop12",
  18. "deop13",
  19. "deop14",
  20. "deop15",
  21. "deop16",
  22. "deop17",
  23. "deop18",
  24. "deop19",
  25. "deop20",
  26. "deop21",
  27. "deop22",
  28. "deop23",
  29. "deop24",
  30. "deop25",
  31. "deop26",
  32. "deop27",
  33. "deop28",
  34. "deop29",
  35. "deho02",
  36. "deni02",
  37. ],
  38. "date_filter": "'2019-01-01'",
  39. "source_dsn": {
  40. "user": "sa",
  41. "pass": "Mffu3011#",
  42. "server": "GC-SERVER1\\GLOBALCUBE",
  43. "database": "desk01",
  44. "driver": "mssql",
  45. },
  46. "source_schema": "dbo",
  47. "source_query": "Belege_Planung_Ist_FC.sql",
  48. "source_header": [
  49. "Datenbank",
  50. "Betrieb_Nr",
  51. "Marke",
  52. "Konto_Nr",
  53. "Bookkeep_Period",
  54. "Betrag",
  55. "Menge",
  56. ],
  57. "target_csv": "Belege_Planung_Ist_FC.csv",
  58. }
  59. def db_import(select_query, source_db, current_table, target_db, target_schema):
  60. pd.read_sql(select_query, source_db).to_sql(
  61. current_table["target"],
  62. target_db,
  63. schema=target_schema,
  64. index=False,
  65. if_exists="append",
  66. )
  67. source_db = create_engine(conn_string(cfg["source_dsn"]))
  68. with open(cfg["source_query"], "r") as f:
  69. select_query = f.read()
  70. with open(cfg["target_csv"], "w") as f:
  71. f.write(";".join(cfg["source_header"]) + "\n")
  72. for current_client in cfg["clients"]:
  73. current_query = select_query.replace("desk01", current_client)
  74. pd.read_sql(current_query, source_db).to_csv(
  75. cfg["target_csv"],
  76. sep=";",
  77. decimal=",",
  78. encoding="latin-1",
  79. index=False,
  80. header=False,
  81. mode="a",
  82. )
  83. print(current_client)