-
Notifications
You must be signed in to change notification settings - Fork 0
/
DbConnector.py
44 lines (37 loc) · 1.7 KB
/
DbConnector.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
import mysql.connector as mysql
class DbConnector:
"""
Connects to the MySQL server on the Ubuntu virtual machine.
Connector needs HOST, DATABASE, USER and PASSWORD to connect,
while PORT is optional and should be 3306.
Example:
HOST = "tdt4225-00.idi.ntnu.no" // Your server IP address/domain name
DATABASE = "testdb" // Database name, if you just want to connect to MySQL server, leave it empty
USER = "testuser" // This is the user you created and added privileges for
PASSWORD = "test123" // The password you set for said user
"""
def __init__(self,
HOST="tdt4225-17.idi.ntnu.no",
DATABASE="group_17_db",
USER="testuser",
PASSWORD="test123"):
# Connect to the database
try:
self.db_connection = mysql.connect(host=HOST, database=DATABASE, user=USER, password=PASSWORD, port=3306)
except Exception as e:
print("ERROR: Failed to connect to db:", e)
# Get the db cursor
self.cursor = self.db_connection.cursor()
print("Connected to:", self.db_connection.get_server_info())
# get database information
self.cursor.execute("select database();")
database_name = self.cursor.fetchone()
print("You are connected to the database:", database_name)
print("-----------------------------------------------\n")
def close_connection(self):
# close the cursor
self.cursor.close()
# close the DB connection
self.db_connection.close()
print("\n-----------------------------------------------")
print("Connection to %s is closed" % self.db_connection.get_server_info())