Advertisement
Guest User

Untitled

a guest
Dec 5th, 2020
170
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.25 KB | None | 0 0
  1. import pandas as pd
  2. import sqlalchemy as sa
  3.  
  4. engine = sa.create_engine("postgresql://scott:tiger@192.168.0.199/test")
  5.  
  6. # set up test environment
  7. tbl = sa.Table(
  8.     "author",
  9.     sa.MetaData(),
  10.     sa.Column("id", sa.Integer, primary_key=True, autoincrement=False),
  11.     sa.Column("name", sa.Unicode(50)),
  12.     sa.Column("title", sa.Unicode(10)),
  13. )
  14. tbl.drop(engine, checkfirst=True)
  15. tbl.create(engine)
  16. with engine.begin() as conn:
  17.     conn.execute(tbl.insert(), {"id": 1, "name": "Unknown"})
  18.  
  19. # create test data
  20. df = pd.DataFrame(
  21.     [('Edwin "Buzz" Aldrin', "Mr", 1)], columns=["name", "title", "id"]
  22. )
  23.  
  24. # run test
  25. df.name = df.name.str.replace("'", "''")
  26. df.title = df.title.str.replace("'", "''")
  27. query = sa.text("""
  28.            INSERT INTO author(name, title, id)
  29.            VALUES %s
  30.            ON CONFLICT (id)
  31.            DO  UPDATE SET name= excluded.name,
  32.                           title= excluded.title
  33.     """ % ','.join([str(i) for i in list(df.to_records(index=False))]).replace('"', "'"))
  34. engine.execute(query)
  35. """console output:
  36. sqlalchemy.exc.ProgrammingError: (psycopg2.errors.SyntaxError) syntax error at or near "Buzz"
  37. LINE 3:             VALUES ('Edwin 'Buzz' Aldrin', 'Mr', 1)
  38.                                    ^
  39. """
  40.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement