alexandre-c

arq_python

Oct 26th, 2019
113
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import psycopg2
  2. import io
  3. import json
  4.  
  5. from psycopg2.extras import Json
  6. from psycopg2.extensions import register_adapter
  7.  
  8. try:
  9.     connection = psycopg2.connect(user = "parking",password = "pg2019",host = "172.17.0.2",port = "5432",database = "parkingdb")
  10.  
  11.     cursor = connection.cursor()
  12.  
  13.     gravar = []
  14.     with open('/dados_json2/arq.json') as f:
  15.         for line in f:
  16.             gravar.append(json.loads(line))
  17.  
  18.     for item in gravar:
  19.         #my_data = item
  20.         my_data = json.dumps(item)
  21.         cursor.execute("INSERT INTO parking VALUES (%s)", (my_data, ))
  22.  
  23.  
  24.     connection.commit()
  25.    
  26.     print("Ok, sucesso !")
  27.  
  28. except (Exception, psycopg2.Error) as error :
  29.     print ("Error while connecting to PostgreSQL", error)
  30. finally:
  31.     #closing database connection.
  32.         if(connection):
  33.             cursor.close()
  34.             connection.close()
  35.             print("PostgreSQL connection is closed")
RAW Paste Data