So i have a simple mysql class that i made:
import mysql.connector as connector
username = 'username'
dbname = 'database'
host = 'localhost'
password = 'password'
port = 3306
class Connection:
def __init__(self):
self.connection = connector.connect(user=username, password=password,host=host,port=port,database=dbname,use_unicode=True)
def execute_and_fetch(self,cmd):
cursor = self.connection.cursor(dictionary=True)
cursor.execute(cmd)
try:
rows = cursor.fetchall()
except connector.errors.InterfaceError:
return None
cursor.close()
return rows
def commit(self):
self.connection.commit()
def close(self):
self.connection.close()
and when i want to avoid sql errors like "you can't execute this command right now", or something like that, i have to use it like this:
from db import Connection
database = Connection()
result = database.execute_and_fetch("SELECT nickname FROM users WHERE id=3")
users = []
#i mean, there must be a proper way to deal with the result?
for item in results:
users.append(item['nickname'])
print(users)
database.close()
#now i need to do another command and to avoid the sql out of commands error i always have to close a connection and reopen it
database = Connection()
result = database.execute_and_fetch("SELECT nickname FROM users WHERE id=3")
......
database.close()
i want to know the shortest and 100% correct way to deal with it every time i try to execute a command or even fetch the results from that command Thanks in advance