Advertisement
alex0sunny

mogrify test

Jul 16th, 2023 (edited)
1,177
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.18 KB | None | 0 0
  1. import io
  2.  
  3. import psycopg
  4.  
  5. dsn = {
  6.     'dbname': 'movies_database',
  7.     'user': 'app',
  8.     'password': '123qwe',
  9.     'host': 'localhost',
  10.     'port': 5432,
  11.     'options': '-c search_path=content',
  12. }
  13.  
  14. if __name__ == '__main__':
  15.     with psycopg.connect(**dsn) as conn, conn.cursor() as cursor:
  16.         cursor.execute("""TRUNCATE content.temp_table""")
  17.  
  18.         data = ('ca211dbc-a6c6-44a5-b238-39fa16bbfe6c', 'Иван Иванов')
  19.         cursor.execute("""INSERT INTO content.temp_table (id, name) VALUES (%s, %s)""", data)
  20.  
  21.         # my code here
  22.         values = [(34545, 'samuel', 48000.0),
  23.                   (34546, 'rachel', 23232),
  24.                   (34547, 'Sean', 92000.0)]
  25.         args = ','.join(cursor.mogrify("(%s,%s,%s)", item) for item in values)
  26.  
  27.         data = [
  28.             ('b8531efb-c49d-4111-803f-725c3abc0f5e', 'Василий Васильевич'),
  29.             ('2d5c50d0-0bb4-480c-beab-ded6d0760269', 'Пётр Петрович'),
  30.         ]
  31.         cursor.executemany('INSERT INTO content.temp_table (id, name) VALUES (%s, %s)', data)
  32.  
  33.  
  34.         data = ('ca211dbc-a6c6-44a5-b238-39fa16bbfe6c', 'Иван Петров')
  35.         cursor.execute(
  36.         """
  37.        INSERT INTO content.temp_table (id, name)
  38.        VALUES (%s, %s)
  39.        ON CONFLICT (id) DO UPDATE SET name=EXCLUDED.name
  40.        """,
  41.             data,
  42.         )
  43.  
  44.         cursor.execute("""SELECT name FROM content.temp_table WHERE id = 'ca211dbc-a6c6-44a5-b238-39fa16bbfe6c'""")
  45.         result = cursor.fetchone()
  46.         print('Результат выполнения команды UPSERT ', result)
  47.  
  48.         cursor.execute("""TRUNCATE content.temp_table""")
  49.         data = io.StringIO()
  50.         data.write('ca211dbc-a6c6-44a5-b238-39fa16bbfe6c,Михаил Михайлович')
  51.         data.seek(0)
  52.  
  53.         with cursor.copy("""COPY content.temp_table FROM STDIN (FORMAT 'csv', HEADER false)""") as copy:
  54.             copy.write(data.read())
  55.  
  56.         cursor.execute("""SELECT name FROM content.temp_table WHERE id = 'ca211dbc-a6c6-44a5-b238-39fa16bbfe6c'""")
  57.         result = cursor.fetchone()
  58.         print('Результат выполнения команды COPY ', result)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement