Skip to content

Instantly share code, notes, and snippets.

@syuraj
Created June 20, 2020 03:34
Show Gist options
  • Save syuraj/e24692d4b114ce7d62fa694b7221e8ec to your computer and use it in GitHub Desktop.
Save syuraj/e24692d4b114ce7d62fa694b7221e8ec to your computer and use it in GitHub Desktop.
Python Postgres Getting Started
import psycopg2
try:
connection = psycopg2.connect("postgres://postgres:@localhost:5432/postgres")
cursor = connection.cursor()
# create_table_query = '''CREATE TABLE mobile
# (ID INT PRIMARY KEY NOT NULL,
# MODEL TEXT NOT NULL,
# PRICE REAL); '''
# cursor.execute(create_table_query)
# connection.commit()
# postgres_insert_query = """ INSERT INTO mobile (ID, MODEL, PRICE) VALUES (%s,%s,%s)"""
# record_to_insert = (5, 'One Plus 6', 950)
# cursor.execute(postgres_insert_query, record_to_insert)
# connection.commit()
sql_select_query = """select * from mobile where id = %s"""
cursor.execute(sql_select_query, (5, ))
record = cursor.fetchone()
print(record)
sql_update_query = """Update mobile set price = %s where id = %s"""
cursor.execute(sql_update_query, (111, 5))
connection.commit()
count = cursor.rowcount
print(count, "Record Updated successfully ")
except (Exception, psycopg2.DatabaseError) as error :
print ("Error while creating PostgreSQL table", error)
finally:
#closing database connection.
if(connection):
cursor.close()
connection.close()
print("PostgreSQL connection is closed")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment