cet.py 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  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. return txt
  29. def queryout(dsn, query, csv_file, codepage, errorlog):
  30. if path.exists(query):
  31. with open(query, 'r', encoding=codepage) as frh:
  32. query = frh.read()
  33. try:
  34. conn = pyodbc.connect(dsn)
  35. cursor = conn.cursor()
  36. cursor.execute(query)
  37. with open(csv_file, 'w', encoding=codepage) as fwh:
  38. while row := cursor.fetchone():
  39. fwh.write('\t'.join(map(convert_data, row)) + '\n')
  40. except pyodbc.InterfaceError as e:
  41. print(e.args[1])
  42. if __name__ == '__main__':
  43. plac.call(run)