python3 + postgresql write sql query into a table code example
Example 1: psycopg2 select example
import psycopg2
try:
connection = psycopg2.connect(user="sysadmin",
password="pynative@#29",
host="127.0.0.1",
port="5432",
database="postgres_db")
cursor = connection.cursor()
postgreSQL_select_Query = "select * from mobile"
cursor.execute(postgreSQL_select_Query)
print("Selecting rows from mobile table using cursor.fetchall")
mobile_records = cursor.fetchall()
print("Print each row and it's columns values")
for row in mobile_records:
print("Id = ", row[0], )
print("Model = ", row[1])
print("Price = ", row[2], "\n")
except (Exception, psycopg2.Error) as error :
print ("Error while fetching data from PostgreSQL", error)
finally:
if(connection):
cursor.close()
connection.close()
print("PostgreSQL connection is closed")
Example 2: insert into database query psycopg2
import psycopg2
conn = psycopg2.connect(host=pg_credential.hostname,
port=pg_credential.port,
user=pg_credential.username,
password=pg_credential.password,
database=pg_credential.path[1:])
cursor = conn.cursor()
cursor.execute("INSERT INTO a_table (c1, c2, c3) VALUES(%s, %s, %s)", (v1, v2, v3))
conn.commit()
cursor.close()
conn.close()