HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythonMinor

Python Connection with MySQL

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
withmysqlpythonconnection

Problem

I want to share something with this community. I did a class connection between Python and MySQL. I hope you can help me with this project and help me do a better class.

Here is the class connection code:

``
import mysql

__author__ = 'Alejandro'
import mysql.connector
from mysql.connector import errorcode

class Mysql(object):
__instance = None

__host = None
__user = None
__password = None
__database = None

__session = None
__connection = None

def __new__(cls, *args, **kwargs):
if not cls.__instance:
cls.__instance = super(Mysql, cls).__new__(cls, *args, **kwargs)
return cls.__instance

def __init__(self, host='localhost', user='root', password='', database=''):
self.__host = host
self.__user = user
self.__password = password
self.__database = database

#Open connection with database
def _open(self):
try:
cnx = mysql.connector.connect(host=self.__host, user=self.__user, password=self.__password,
database=self.__database)
self.__connection = cnx
self.__session = cnx.cursor()
except mysql.connector.Error as err:
if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
print 'Something is wrong with your user name or password'
elif err.errno == errorcode.ER_BAD_DB_ERROR:
print 'Database does not exists'
else:
print err

def _close(self):
self.__session.close()
self.__connection.close()

def insert(self, table, *args, **kwargs):
values = None
query = "INSERT INTO %s " % table
if kwargs:
keys = kwargs.keys()
values = kwargs.values()
query += "(" + ",".join(["
%s`"]len(keys)) % tuple(keys) + ") VALUES(" + ",".join(["%s"]len(values)) + ")"
elif args:
values = args
query += " VAL

Solution

Everything looks quite neat. Here are a few comments.

query = "SELECT "
    l = len(keys) - 1
    for i, key in enumerate(keys):
        query += "`"+key+"`"
        if i < l:
            query += ","
    query += " FROM %s" % table


can be rewritten :

query =  "SELECT `" + "`,`".join(keys) + "` FROM " + table


(I know that string concatenation might not be the best but it's just to join how you could use join to do what you want to do). The same kind of argument would hold for update.

In select and in call_store_procedure, is this :

for result in self.__session.stored_results():
        result = result.fetchall()


any better than :

for result in self.__session.stored_results():
        result.fetchall()


?

Also, just some food for thought as I haven't studied the issue in depth : how do you handle parameters that don't need to be in quotes such as numbers ?

Code Snippets

query = "SELECT "
    l = len(keys) - 1
    for i, key in enumerate(keys):
        query += "`"+key+"`"
        if i < l:
            query += ","
    query += " FROM %s" % table
query =  "SELECT `" + "`,`".join(keys) + "` FROM " + table
for result in self.__session.stored_results():
        result = result.fetchall()
for result in self.__session.stored_results():
        result.fetchall()

Context

StackExchange Code Review Q#39009, answer score: 3

Revisions (0)

No revisions yet.