Connect To PostgreSQL Database Server using Python
This tutorial teaches us how we can connect to the PostgreSQL Database Server using Python programming. As we all know that to connect to a database or something like that, we need to deal with a Python library that would help us do so. The most common Python library for PostgreSQL is psycopg. We are going to use this library client to connect to our database.
Installing psycopg package
If you are using anaconda, write this line in the terminal window of your system.
conda install psycopg2
This will install the psycopg in your system.
If you want to install it from pip, then below is given the command:
pip install psycopg2
Follow this link to learn how to install PostgreSQL according to your system properties:
Connecting to PostgreSQL server
Now after installing the library, open your Python shell and import the psycopg2 library. Run the following Python code to connect to the PostgreSQL server and check if the code works properly and command to create the table is executed successfully.
import psycopg2 con = psycopg2.connect(dbname="codespeedy", user="codespeedy") con.autocommit = True cursor = con.cursor() cursor.execute("CREATE TABLE account(id integer PRIMARY KEY, name text, amount float)") con.close()
- First, we import the psycopg2 library.
- Make a connection using the .connect method of psycopg2 lib.
- Make autocommit = True so that autocommit happens automatically.
- Now we make a cursor object and assign it to the cursor variable.
- Now we make a query using the cursor and make a table in the current database.
- Close the connection.
I hope you liked the article. Comment if you have any doubts or suggestions regarding this article.
You can also read other articles related to this. Click the links given below.
Leave a Reply