cet.py 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  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(query, mode, csv_file, Server='localhost\\GLOBALCUBE', database='master',
  15. User='sa', Password='Mffu3011#', charset=False, Codepage='65001', errorlog='error.log'):
  16. dsn = f"dsn={Server};uid={User};pwd={Password}"
  17. if Codepage.isnumeric():
  18. Codepage = 'cp' + Codepage
  19. if mode == 'queryout':
  20. queryout(dsn, query, csv_file, Codepage, errorlog)
  21. return
  22. print('This is madness')
  23. def convert_data(element):
  24. txt = str(element)
  25. txt = txt.replace('None', '')
  26. txt = txt.replace('False', '0').replace('True', '1')
  27. txt = txt.replace('\t', '').replace('\r', '').replace('\n', '')
  28. txt = txt.replace('\x81', '').replace('\x90', '')
  29. return txt
  30. def queryout(dsn, query, csv_file, codepage, errorlog):
  31. if path.exists(query):
  32. with open(query, 'r', encoding=codepage) as frh:
  33. query = frh.read()
  34. try:
  35. conn = pyodbc.connect(dsn)
  36. cursor = conn.cursor()
  37. cursor.execute(query)
  38. except pyodbc.InterfaceError as e:
  39. print(e.args[1])
  40. with open(csv_file, 'w', encoding=codepage) as fwh:
  41. while row := cursor.fetchone():
  42. try:
  43. fwh.write(('\t'.join(map(convert_data, row)) + '\n'))
  44. except pyodbc.DataError as e:
  45. print(e.args[1])
  46. if __name__ == '__main__':
  47. plac.call(run)