Connect To PostgreSQL Database Server and Execute SQL Statement in Python
Hello everyone, in today article , I will talk in detail how to connect to the PostgreSQL database and execute sql statement in python.
First add psycopg2 package to the project
2 |
import psycopg2 |
If you recieve an error “no module name” , perform the install package as follows.
if you recieve an error Installing packages: error occurred , perform the install package as follows command line
2 3 4 5 6 7 8 9 |
sudo apt-get install postgresql sudo apt-get install python-psycopg2 sudo apt-get install libpq-dev |
For you connection can use a list of keyword arguments:
2 3 |
connection = psycopg2.connect(host="localhost",database="dbname", user="username", password="password") |
Create Cursor
2 |
cursor = connect.cursor() |
Execute Statement
2 |
cursor.execute('SELECT *from layername') |
Display the return values
2 |
cur.fetchone() |
Display Output :
Other Sql Script Example
Insert SQL :
2 3 4 5 |
cursor = connection.cursor() cursor.execute("INSERT INTO a_table (c1, c2, c3) VALUES(%s, %s, %s)", (v1, v2, v3)) cursor.close() connnection.close() |
Update SQL:
2 3 4 5 |
cursor = connection.cursor() cursor.execute("UPDATE table_name SET update_column_name=(%s) WHERE ref_column_id_value = (%s)", ("column_name","value_you_want_to_update",)); connection.commit() cursor.close() |
Delete SQL:
2 3 4 |
cursor.execute("DELETE FROM parts WHERE part_id = %s", (part_id,)) cursor.close() connection.close() |
if you have question do not forget to write from the chat button next to it or from the comment
Recent Comments