Reputation: 63
I'm quite new into using databases with python. My question is: I'm creating a class "Database" from the mysql.connector in which I'm implementing some methods inside this class to create tables, delete tables, etc... I want to know if it is right to create a class variable which is the connector(mysql.connect()
). I mean, can I keep the connection on while the application is open, or should I open and close the connection on each query? The main purpose of this Database class I'm creating is to use as a query mechaninsm in another app.
Another question is: how the cursor works. Should I create and close a cursor for each query, or can I do the way I'm doing: creating a self.cursor
and calling it on each query I want?
import mysql.connector as mysql
from mysql.connector import errorcode
class Database(object):
def __init__(self, host, user, user_pass, database_name):
self.host, self.database_name = host, database_name
self.user, self.user_pass = user, user_pass
try:
self.connect = mysql.connect(
host= host, user= user,
passwd= user_pass, database= database_name
)
print("Successfully connected to database: {}.".format(database_name))
self.cursor = self.connect.cursor()
self.tables = self.get_all_tables()
except mysql.Error as err:
print(err)
def create_table(self, table_name, columns): #<-- expects a string and a list of tuples
command = ['{} {}'.format(col[0], col[1]) for col in columns]
command = ', '.join(command)
try:
self.cursor.execute("CREATE TABLE {} ({});".format(table_name, command))
print("Table \"{}\" successfully created.".format(table_name))
except mysql.Error as err:
if err.errno == errorcode.ER_TABLE_EXISTS_ERROR:
print("Table \"{}\" already exists.".format(table_name))
else:
print(err)
def remove_table(self, table_name):
try:
self.cursor.execute("DROP TABLE {};".format(table_name))
print("Table \"{}\" removed.".format(table_name))
except mysql.Error as err:
print(err)
if __name__ == "__main__":
#Configuring the database
DATABASE_NAME = 'company_employees'
config = {
'host': 'localhost',
'user': 'root',
'pass': 'rootpass123',
'db': DATABASE_NAME # <-- Connects to database accounts
}
db = Database(config['host'], config['user'],
config['pass'], config['db'])
Upvotes: 2
Views: 332