Guest User

Untitled

a guest
Jul 26th, 2018
142
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.53 KB | None | 0 0
  1. import psycopg2
  2.  
  3. database = ''
  4. host = 'localhost'
  5. port = 5432
  6. user = ''
  7. password = ''
  8.  
  9. table = ''
  10.  
  11. conn = psycopg2.connect(dbname=database,
  12. host=host,
  13. port=port,
  14. user=user,
  15. password=password)
  16.  
  17. conn.autocommit = True
  18. census_ct_id_cur = conn.cursor()
  19. census_ct_id_cur.execute("SELECT geo_id FROM {table};".format(table=table))
  20. for i in census_ct_id_cur.fetchall():
  21. old_ct = i[0]
  22. old_ct_split = i[0].split('.')
  23. if len(old_ct_split) > 1:
  24. old_decimals = old_ct_split[1]
  25. if len(old_decimals) == 1:
  26. new_decimals = "{}0".format(old_decimals)
  27. elif len(old_decimals) == 2:
  28. new_decimals = old_decimals
  29. else:
  30. print("Edge case, more than two decimal places...?")
  31.  
  32. elif len(old_ct_split) == 1:
  33. new_decimals = '00'
  34. else:
  35. print("Edge case, more than one period in string...")
  36.  
  37. old_whole_numbers = old_ct_split[0]
  38. new_whole_numbers = (
  39. '0' * (7 - int(len(old_whole_numbers)))) + old_whole_numbers
  40.  
  41. new_ct_id = new_whole_numbers + '.' + new_decimals
  42.  
  43. if new_ct_id != old_ct:
  44. update_query = """
  45. UPDATE {table}
  46. SET geo_id = '{new_ct_id}'
  47. WHERE geo_id = '{old_ct}'
  48. """.format(
  49. table=table,
  50. new_ct_id=new_ct_id,
  51. old_ct=old_ct
  52. )
  53. print(update_query)
  54. ct_update_cur = conn.cursor()
  55. ct_update_cur.execute(update_query)
  56. print('update query executed')
Add Comment
Please, Sign In to add comment