Function - Get Database Connection¶
Let us develop function to get Database Connection so that we can reuse in subsequent topics to perform CRUD Operations.
get_connection
will take required paramters to establish a connection to the database and return connection object.We can invoke that function and create required connection objects such as
sms_connection
so that we can perform database operations.sms_connection
is the connection object for our hypothetical sms database.We can trigger this notebook from other notebooks by using
%run
.The function as well as objects such as
sms_connection
can be used in the other notebooks from which this notebook is triggered.In the similar lines we can have connection object
retail_connection
for retail database.
import psycopg2
def get_connection(host, port, database, user, password):
connection = None
try:
connection = psycopg2.connect(
host=host,
port=port,
database=database,
user=user,
password=password
)
except Exception as e:
raise(e)
return connection
host = 'localhost'
port = '5432'
database = 'itversity_sms_db'
user = 'itversity_sms_user'
password = 'sms_password'
sms_connection = get_connection(
host=host,
port=port,
database=database,
user=user,
password=password
)
host = 'localhost'
port = '5432'
database = 'itversity_retail_db'
user = 'itversity_retail_user'
password = 'retail_password'
retail_connection = get_connection(
host=host,
port=port,
database=database,
user=user,
password=password
)