Guest User

Untitled

a guest
Apr 14th, 2018
175
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.47 KB | None | 0 0
  1. import psycopg2, os
  2.  
  3. fields_dict = {}
  4.  
  5. with open('../docfields.txt') as file:
  6.  
  7. lines = file.readlines()
  8.  
  9. for line in lines:
  10.  
  11. names = line.split(' -')
  12.  
  13. if len(names) > 1:
  14. names = names[:len(names) - 1]
  15.  
  16. names = ''.join(names).split(', ')
  17.  
  18. for name in names:
  19.  
  20. fields_dict[name] = names[0]
  21.  
  22. con = psycopg2.connect(host='localhost', database='datasus', user='postgres', password='')
  23.  
  24. cur = con.cursor()
  25.  
  26. try:
  27.  
  28. cur.execute('select * from "datasus_table"')
  29.  
  30. except Exception as e:
  31.  
  32. print('You need to create "datasus_table" in database before executing this script...')
  33.  
  34. print('Just run script.sql file...')
  35.  
  36. exit(1)
  37.  
  38. files = os.listdir('../data_files/')
  39.  
  40. for file in files:
  41.  
  42. name = file.split('.')[0]
  43.  
  44. sql = 'select * from "' + name + '"'
  45.  
  46. cur.execute(sql)
  47. recset = cur.fetchall()
  48.  
  49. fields = cur.description
  50. size = len(cur.description)
  51.  
  52. for rec in recset:
  53.  
  54. insert_qry = 'insert into "datasus_table" ('
  55.  
  56. for i in range(0, size):
  57.  
  58. insert_qry += '"' + fields_dict[fields[i].name] + '"' + (') values (' if i == size - 1 else ',')
  59.  
  60. for i in range(0, len(rec)):
  61.  
  62. insert_qry += ('\'' + (str(rec[i]) + '\'') if rec[i] else 'null') + (')' if i == len(rec) - 1 else ',')
  63.  
  64. print('Consulta: ' + insert_qry)
  65.  
  66. cur_insert = con.cursor()
  67.  
  68. cur_insert.execute(insert_qry)
  69.  
  70. con.commit()
  71.  
  72. cur_insert.close()
  73.  
  74. cur.close()
  75. con.close()
Add Comment
Please, Sign In to add comment