Skip to content

Instantly share code, notes, and snippets.

@ShahrozTanveer
Last active January 29, 2021 19:20
Show Gist options
  • Save ShahrozTanveer/bc2a7fa1d86b68d7744638a570ce2925 to your computer and use it in GitHub Desktop.
Save ShahrozTanveer/bc2a7fa1d86b68d7744638a570ce2925 to your computer and use it in GitHub Desktop.
Simple use of PostgresSql in Python using psycopg2
import psycopg2
#Create Connection to PostgreSQL
connection = psycopg2.connect(
host = "localhost",
database="system",
user = "<your user name>",
password = "<your password>")
# Open a cursor to perform database operations
cursor = connection.cursor()
#execute your query (insert in users table)
cursor.execute("insert into users (id, email, password) values (%s, %s, %s)", (1, "[email protected]", "root") )
#execute your query (get data from users table)
cursor.execute("select id, email, password from users")
#fetchall=> Fetch all (remaining) rows of a query result, returning them as a list of tuples. An empty list is returned if there is no more record to fetch
rows = cursor.fetchall()
for row in rows:
print(row)
#Commit any pending transaction to the database.
connection.commit()
#close the cursor
cursor.close()
#close the connection
connection.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment