PostgreSQL Connection
Install Module:
pip install psycopg22. Connection string:
conn = psycopg2.connect("dbname=suppliers user=postgres password=postgres")or use as a list:
conn = psycopg2.connect(
host="localhost",
database="suppliers",
user="postgres",
password="Abcd1234")To make it more convenient, you can use a configuration file to store all connection parameters. The following shows the contents of the database.ini file:
[postgresql]
host=localhost
database=suppliers
user=postgres
password=SecurePas$1By using the database.ini, you can change the PostgreSQL connection parameters when you move the code to the production environment without modifying the code.
Notice that if you git, you need to add the database.ini to the .gitignore file to not committing the sensitive information to the public repo like github. The .gitignore file will be like this:
The following config() function read the database.ini file and returns connection parameters. The config() function is placed in the config.py file:
The following connect() function connects to the suppliers database and prints out the PostgreSQL database version
How it works:
First, read database connection parameters from the
database.inifile.Next, create a new database connection by calling the
connect()function.Then, create a new
cursorandexecuteanSQLstatement to get the PostgreSQL database version.After that, read the result set by calling the
fetchone()method of the cursor object.Finally,
closethecommunicationwith thedatabaseserver by calling theclose()method of the cursor and connection objects.
Last updated