cet.py 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. import plac
  2. import pyodbc
  3. from os import path
  4. @plac.pos("query", "SQL Query", type=str)
  5. @plac.pos("mode", "", choices=["in", "out", "queryout"])
  6. @plac.pos("csv_file", "", type=str)
  7. @plac.opt("Server", "Hostname or DSN", type=str)
  8. @plac.opt("database", "", type=str)
  9. @plac.opt("User", "", type=str)
  10. @plac.opt("Password", "", type=str)
  11. @plac.flg("charset", "")
  12. @plac.opt("Codepage", "", type=str)
  13. @plac.opt("errorlog", "", type=str)
  14. def run(
  15. query,
  16. mode,
  17. csv_file,
  18. Server="localhost\\GLOBALCUBE",
  19. database="master",
  20. User="sa",
  21. Password="Mffu3011#",
  22. charset=False,
  23. Codepage="65001",
  24. errorlog="error.log",
  25. ):
  26. dsn = f"dsn={Server};uid={User};pwd={Password}"
  27. if Codepage.isnumeric():
  28. Codepage = "cp" + Codepage
  29. if mode == "queryout":
  30. queryout(dsn, query, csv_file, Codepage, errorlog)
  31. return
  32. print("This is madness")
  33. def convert_data(element):
  34. txt = str(element)
  35. txt = txt.replace("None", "")
  36. txt = txt.replace("False", "0").replace("True", "1")
  37. txt = txt.replace("\t", "").replace("\r", "").replace("\n", "")
  38. txt = txt.replace("\x81", "").replace("\x90", "")
  39. return txt
  40. def queryout(dsn, query, csv_file, codepage, errorlog):
  41. if path.exists(query):
  42. with open(query, "r", encoding=codepage) as frh:
  43. query = frh.read()
  44. try:
  45. conn = pyodbc.connect(dsn)
  46. cursor = conn.cursor()
  47. cursor.execute(query)
  48. except pyodbc.InterfaceError as e:
  49. print(e.args[1])
  50. with open(csv_file, "w", encoding=codepage) as fwh:
  51. while row := cursor.fetchone():
  52. try:
  53. fwh.write(("\t".join(map(convert_data, row)) + "\n"))
  54. except pyodbc.DataError as e:
  55. print(e.args[1])
  56. if __name__ == "__main__":
  57. plac.call(run)