Last active
January 29, 2021 19:20
-
-
Save ShahrozTanveer/bc2a7fa1d86b68d7744638a570ce2925 to your computer and use it in GitHub Desktop.
Simple use of PostgresSql in Python using psycopg2
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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