Guest User

Untitled

a guest
Jul 17th, 2018
90
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.96 KB | None | 0 0
  1. [{"1":"1","2":"1"},...]
  2.  
  3. import pandas as pd
  4. from sqlalchemy import create_engine
  5.  
  6. data = [{'a':1, 'b':'string1'}, {'a':2, 'b':'string2'}, {'a':3, 'b':'string3'}]
  7.  
  8. # create SQL Alchemy DB connection
  9. # conn = create_engine('postgresql://user:password@host:port/dbname')
  10. conn = create_engine('postgresql+psycopg2://user:password@host:port/dbname')
  11.  
  12. # create Pandas DataFrame from the list of records
  13. df = pd.DataFrame(data)
  14.  
  15. # write DF into SQL table
  16. df.to_sql('table_name', conn, if_exists='replace', index=False)
  17.  
  18. In [74]: df
  19. Out[74]:
  20. a b
  21. 0 1 string1
  22. 1 2 string2
  23. 2 3 string3
  24.  
  25. import psycopg2
  26.  
  27. out = [{'a':1,'b':2,'c':3}, {'a':4,'b':5,'c':6}]
  28.  
  29. with psycopg2.connect("dbname='dbname' user='user' host='host' password='password'") as conn1:
  30. with conn1.cursor() as cur:
  31. cur.execute("CREATE TABLE table (a varchar, b varchar, c varchar);")
  32. cur.executemany("INSERT INTO table VALUES (%(a)s, %(b)s, %(c)s);", out)
  33. conn1.commit()
Add Comment
Please, Sign In to add comment