Home > Blockchain >  psycopg2 with Postgres fetchall works but not execute
psycopg2 with Postgres fetchall works but not execute

Time:06-18

I am trying to execute some Postgres queries with psycopg2.

import psycopg2

conn = psycopg2.connect(
    host="test.postgres.database.azure.com",
    database="postgres",
    user="test",
    password="test")
cur = conn.cursor()

sql = "select site_panel from test.ws_sites"

cur.execute(sql)
rows =  cur.fetchall()

The query above works well and returns the data but the following query does not delete the table as intended.

 cur.execute ("DROP TABLE IF EXISTS test.ws_sites")

Anything wrong I'm doing here?

CodePudding user response:

A query that modifies table data or schema structure needs to be committed:

cur.execute ("DROP TABLE IF EXISTS test.ws_sites")
conn.commit()

Alternatively, place

conn.autocommit = True

after creating the connection.

  • Related