-
Notifications
You must be signed in to change notification settings - Fork 0
/
connection.py
64 lines (56 loc) · 1.79 KB
/
connection.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
import mysql.connector
from decouple import config
from dotenv import load_dotenv
import os
# check if USE_ENV is set to True
use_env = os.environ.get("USE_ENV")
if use_env != "True":
load_dotenv()
dbase = os.getenv("DBASE")
duser = os.getenv("DUSER")
dpw = os.getenv("DPASS")
dip = os.getenv("DHOST")
else:
# load environment variables instead of .env file
dbase = os.environ.get("DBASE")
duser = os.environ.get("DUSER")
dpw = os.environ.get("DPASS")
dip = os.environ.get("DHOST")
# Define a function to open database connection
def open_db_connection(db_name, user, password, host):
# Try to connect to the database
try:
# Create a connection object with the name mydb
mydb = mysql.connector.connect(database=db_name, user=user, password=password, host=host)
# Print a success message
print("Opened connection to database:", db_name)
# Return the connection object
return mydb
# Handle any exceptions
except mysql.connector.Error as e:
# Print an error message
print("Failed to open connection to database:", e)
# Return None
return None
# Define a function to close database connection
def close_db_connection(mydb, db_name=dbase):
# Check if the connection object exists
if mydb:
# Try to close the connection
try:
# Close the connection
mydb.close()
# Print a success message
print("Closed connection to database:", db_name)
# Handle any exceptions
except mysql.connector.Error as e:
# Print an error message
print("Failed to close connection to database:", e)
def defineDB():
mydb=open_db_connection(
dbase,
duser,
dpw,
dip,
)
return mydb