Python Connection with MySQL












6












$begingroup$


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 += " VALUES(" + ",".join(["%s"]*len(values)) + ")"
self._open()
self.__session.execute(query, values)
self.__connection.commit()
self._close()
return self.__session.lastrowid

def select(self, table, where=None, *args):
result = None
query = "SELECT "
keys = args
l = len(keys) - 1
for i, key in enumerate(keys):
query += "`"+key+"`"
if i < l:
query += ","
query += " FROM %s" % table
if where:
query += " WHERE %" % where
self._open()
self.__session.execute(query)
self.__connection.commit()
for result in self.__session.stored_results():
result = result.fetchall()
self._close()
return result

def update(self, table, index, **kwargs):
query = "UPDATE %s SET" % table
keys = kwargs.keys()
values = kwargs.values()
l = len(keys) - 1
for i, key in enumerate(keys):
query += "`"+key+"`=%s"
if i < l:
query += ","
query += " WHERE index=%d" % index
self._open()
self.__session.execute(query, values)
self.__connection.commit()
self._close()

def delete(self, table, index):
query = "DELETE FROM %s WHERE uuid=%d" % (table, index)
self._open()
self.__session.execute(query)
self.__connection.commit()
self._close()

def call_store_procedure(self, name, *args):
result_sp = None
self._open()
self.__session.callproc(name, args)
self.__connection.commit()
for result in self.__session.stored_results():
result_sp = result.fetchall()
self._close()
return result_sp


Here is how its use looks like:



from Mysql import Mysql
connection = Mysql(host='localhost', user='root', password='', database='test')
#Assuming that our table have the fields id and name in this order.
#we can use this way but the parameter should have the same order that table
#connection.insert('table_name',parameters to insert)
connection.insert('test',1, 'Alejandro Mora')
#in this case the order isn't matter
#connection.insert('table_name', field=Value to insert)
connection.insert('test',name='Alejandro Mora', id=1)
#connection.select('Table', where="conditional(optional)", field to returned)
connection.select('test', where="name = 'Alejandro Mora' ")
connection.select('test', None,'id','name')
#connection.update('Table', id, field=Value to update)
connection.update('test', 1, name='Alejandro')
#connection.delete('Table', id)
connection.delete('test', 1)
#connection.call_store_procedure(prodecure name, Values)
connection.call_store_procedure('search_users_by_name', 'Alejandro')









share|improve this question











$endgroup$












  • $begingroup$
    Can you explain me which args must passed for Select method here ? cheers
    $endgroup$
    – user97118
    Feb 9 '16 at 11:00
















6












$begingroup$


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 += " VALUES(" + ",".join(["%s"]*len(values)) + ")"
self._open()
self.__session.execute(query, values)
self.__connection.commit()
self._close()
return self.__session.lastrowid

def select(self, table, where=None, *args):
result = None
query = "SELECT "
keys = args
l = len(keys) - 1
for i, key in enumerate(keys):
query += "`"+key+"`"
if i < l:
query += ","
query += " FROM %s" % table
if where:
query += " WHERE %" % where
self._open()
self.__session.execute(query)
self.__connection.commit()
for result in self.__session.stored_results():
result = result.fetchall()
self._close()
return result

def update(self, table, index, **kwargs):
query = "UPDATE %s SET" % table
keys = kwargs.keys()
values = kwargs.values()
l = len(keys) - 1
for i, key in enumerate(keys):
query += "`"+key+"`=%s"
if i < l:
query += ","
query += " WHERE index=%d" % index
self._open()
self.__session.execute(query, values)
self.__connection.commit()
self._close()

def delete(self, table, index):
query = "DELETE FROM %s WHERE uuid=%d" % (table, index)
self._open()
self.__session.execute(query)
self.__connection.commit()
self._close()

def call_store_procedure(self, name, *args):
result_sp = None
self._open()
self.__session.callproc(name, args)
self.__connection.commit()
for result in self.__session.stored_results():
result_sp = result.fetchall()
self._close()
return result_sp


Here is how its use looks like:



from Mysql import Mysql
connection = Mysql(host='localhost', user='root', password='', database='test')
#Assuming that our table have the fields id and name in this order.
#we can use this way but the parameter should have the same order that table
#connection.insert('table_name',parameters to insert)
connection.insert('test',1, 'Alejandro Mora')
#in this case the order isn't matter
#connection.insert('table_name', field=Value to insert)
connection.insert('test',name='Alejandro Mora', id=1)
#connection.select('Table', where="conditional(optional)", field to returned)
connection.select('test', where="name = 'Alejandro Mora' ")
connection.select('test', None,'id','name')
#connection.update('Table', id, field=Value to update)
connection.update('test', 1, name='Alejandro')
#connection.delete('Table', id)
connection.delete('test', 1)
#connection.call_store_procedure(prodecure name, Values)
connection.call_store_procedure('search_users_by_name', 'Alejandro')









share|improve this question











$endgroup$












  • $begingroup$
    Can you explain me which args must passed for Select method here ? cheers
    $endgroup$
    – user97118
    Feb 9 '16 at 11:00














6












6








6


4



$begingroup$


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 += " VALUES(" + ",".join(["%s"]*len(values)) + ")"
self._open()
self.__session.execute(query, values)
self.__connection.commit()
self._close()
return self.__session.lastrowid

def select(self, table, where=None, *args):
result = None
query = "SELECT "
keys = args
l = len(keys) - 1
for i, key in enumerate(keys):
query += "`"+key+"`"
if i < l:
query += ","
query += " FROM %s" % table
if where:
query += " WHERE %" % where
self._open()
self.__session.execute(query)
self.__connection.commit()
for result in self.__session.stored_results():
result = result.fetchall()
self._close()
return result

def update(self, table, index, **kwargs):
query = "UPDATE %s SET" % table
keys = kwargs.keys()
values = kwargs.values()
l = len(keys) - 1
for i, key in enumerate(keys):
query += "`"+key+"`=%s"
if i < l:
query += ","
query += " WHERE index=%d" % index
self._open()
self.__session.execute(query, values)
self.__connection.commit()
self._close()

def delete(self, table, index):
query = "DELETE FROM %s WHERE uuid=%d" % (table, index)
self._open()
self.__session.execute(query)
self.__connection.commit()
self._close()

def call_store_procedure(self, name, *args):
result_sp = None
self._open()
self.__session.callproc(name, args)
self.__connection.commit()
for result in self.__session.stored_results():
result_sp = result.fetchall()
self._close()
return result_sp


Here is how its use looks like:



from Mysql import Mysql
connection = Mysql(host='localhost', user='root', password='', database='test')
#Assuming that our table have the fields id and name in this order.
#we can use this way but the parameter should have the same order that table
#connection.insert('table_name',parameters to insert)
connection.insert('test',1, 'Alejandro Mora')
#in this case the order isn't matter
#connection.insert('table_name', field=Value to insert)
connection.insert('test',name='Alejandro Mora', id=1)
#connection.select('Table', where="conditional(optional)", field to returned)
connection.select('test', where="name = 'Alejandro Mora' ")
connection.select('test', None,'id','name')
#connection.update('Table', id, field=Value to update)
connection.update('test', 1, name='Alejandro')
#connection.delete('Table', id)
connection.delete('test', 1)
#connection.call_store_procedure(prodecure name, Values)
connection.call_store_procedure('search_users_by_name', 'Alejandro')









share|improve this question











$endgroup$




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 += " VALUES(" + ",".join(["%s"]*len(values)) + ")"
self._open()
self.__session.execute(query, values)
self.__connection.commit()
self._close()
return self.__session.lastrowid

def select(self, table, where=None, *args):
result = None
query = "SELECT "
keys = args
l = len(keys) - 1
for i, key in enumerate(keys):
query += "`"+key+"`"
if i < l:
query += ","
query += " FROM %s" % table
if where:
query += " WHERE %" % where
self._open()
self.__session.execute(query)
self.__connection.commit()
for result in self.__session.stored_results():
result = result.fetchall()
self._close()
return result

def update(self, table, index, **kwargs):
query = "UPDATE %s SET" % table
keys = kwargs.keys()
values = kwargs.values()
l = len(keys) - 1
for i, key in enumerate(keys):
query += "`"+key+"`=%s"
if i < l:
query += ","
query += " WHERE index=%d" % index
self._open()
self.__session.execute(query, values)
self.__connection.commit()
self._close()

def delete(self, table, index):
query = "DELETE FROM %s WHERE uuid=%d" % (table, index)
self._open()
self.__session.execute(query)
self.__connection.commit()
self._close()

def call_store_procedure(self, name, *args):
result_sp = None
self._open()
self.__session.callproc(name, args)
self.__connection.commit()
for result in self.__session.stored_results():
result_sp = result.fetchall()
self._close()
return result_sp


Here is how its use looks like:



from Mysql import Mysql
connection = Mysql(host='localhost', user='root', password='', database='test')
#Assuming that our table have the fields id and name in this order.
#we can use this way but the parameter should have the same order that table
#connection.insert('table_name',parameters to insert)
connection.insert('test',1, 'Alejandro Mora')
#in this case the order isn't matter
#connection.insert('table_name', field=Value to insert)
connection.insert('test',name='Alejandro Mora', id=1)
#connection.select('Table', where="conditional(optional)", field to returned)
connection.select('test', where="name = 'Alejandro Mora' ")
connection.select('test', None,'id','name')
#connection.update('Table', id, field=Value to update)
connection.update('test', 1, name='Alejandro')
#connection.delete('Table', id)
connection.delete('test', 1)
#connection.call_store_procedure(prodecure name, Values)
connection.call_store_procedure('search_users_by_name', 'Alejandro')






python mysql






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Jan 11 '14 at 6:12







Alejandro Mora

















asked Jan 10 '14 at 15:42









Alejandro MoraAlejandro Mora

3315




3315












  • $begingroup$
    Can you explain me which args must passed for Select method here ? cheers
    $endgroup$
    – user97118
    Feb 9 '16 at 11:00


















  • $begingroup$
    Can you explain me which args must passed for Select method here ? cheers
    $endgroup$
    – user97118
    Feb 9 '16 at 11:00
















$begingroup$
Can you explain me which args must passed for Select method here ? cheers
$endgroup$
– user97118
Feb 9 '16 at 11:00




$begingroup$
Can you explain me which args must passed for Select method here ? cheers
$endgroup$
– user97118
Feb 9 '16 at 11:00










2 Answers
2






active

oldest

votes


















3












$begingroup$

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 ?






share|improve this answer









$endgroup$













  • $begingroup$
    Hi thanks for the recomendations. I handle those parameters in this way fisrt i make the query sentence leaving all parameters input with %s, why? because i send all parameter in execute method and it ensures to set all values in the query.
    $endgroup$
    – Alejandro Mora
    Jan 11 '14 at 5:20



















0












$begingroup$

An error maybe happen when the number of date base is two or more in your project. Example as:



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

def prin(self):
print(self.__host, self.__user, self.__password, self.__database)

a = Mysql('192.168.1.12', 'user', 'user1234', 'test')
a.prin() # output ('192.168.1.12', 'user', 'user1234', 'test')
b = Mysql('192.168.1.132', 'admin', 'admin1234', 'train')
b.prin() # output ('192.168.1.132', 'admin', 'admin1234', 'train')
a.prin() # output ('192.168.1.132', 'admin', 'admin1234', 'train')
```





share|improve this answer









$endgroup$













    Your Answer





    StackExchange.ifUsing("editor", function () {
    return StackExchange.using("mathjaxEditing", function () {
    StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix) {
    StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["\$", "\$"]]);
    });
    });
    }, "mathjax-editing");

    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "196"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: false,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: null,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f39009%2fpython-connection-with-mysql%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    3












    $begingroup$

    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 ?






    share|improve this answer









    $endgroup$













    • $begingroup$
      Hi thanks for the recomendations. I handle those parameters in this way fisrt i make the query sentence leaving all parameters input with %s, why? because i send all parameter in execute method and it ensures to set all values in the query.
      $endgroup$
      – Alejandro Mora
      Jan 11 '14 at 5:20
















    3












    $begingroup$

    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 ?






    share|improve this answer









    $endgroup$













    • $begingroup$
      Hi thanks for the recomendations. I handle those parameters in this way fisrt i make the query sentence leaving all parameters input with %s, why? because i send all parameter in execute method and it ensures to set all values in the query.
      $endgroup$
      – Alejandro Mora
      Jan 11 '14 at 5:20














    3












    3








    3





    $begingroup$

    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 ?






    share|improve this answer









    $endgroup$



    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 ?







    share|improve this answer












    share|improve this answer



    share|improve this answer










    answered Jan 10 '14 at 16:57









    JosayJosay

    25.8k14087




    25.8k14087












    • $begingroup$
      Hi thanks for the recomendations. I handle those parameters in this way fisrt i make the query sentence leaving all parameters input with %s, why? because i send all parameter in execute method and it ensures to set all values in the query.
      $endgroup$
      – Alejandro Mora
      Jan 11 '14 at 5:20


















    • $begingroup$
      Hi thanks for the recomendations. I handle those parameters in this way fisrt i make the query sentence leaving all parameters input with %s, why? because i send all parameter in execute method and it ensures to set all values in the query.
      $endgroup$
      – Alejandro Mora
      Jan 11 '14 at 5:20
















    $begingroup$
    Hi thanks for the recomendations. I handle those parameters in this way fisrt i make the query sentence leaving all parameters input with %s, why? because i send all parameter in execute method and it ensures to set all values in the query.
    $endgroup$
    – Alejandro Mora
    Jan 11 '14 at 5:20




    $begingroup$
    Hi thanks for the recomendations. I handle those parameters in this way fisrt i make the query sentence leaving all parameters input with %s, why? because i send all parameter in execute method and it ensures to set all values in the query.
    $endgroup$
    – Alejandro Mora
    Jan 11 '14 at 5:20













    0












    $begingroup$

    An error maybe happen when the number of date base is two or more in your project. Example as:



    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

    def prin(self):
    print(self.__host, self.__user, self.__password, self.__database)

    a = Mysql('192.168.1.12', 'user', 'user1234', 'test')
    a.prin() # output ('192.168.1.12', 'user', 'user1234', 'test')
    b = Mysql('192.168.1.132', 'admin', 'admin1234', 'train')
    b.prin() # output ('192.168.1.132', 'admin', 'admin1234', 'train')
    a.prin() # output ('192.168.1.132', 'admin', 'admin1234', 'train')
    ```





    share|improve this answer









    $endgroup$


















      0












      $begingroup$

      An error maybe happen when the number of date base is two or more in your project. Example as:



      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

      def prin(self):
      print(self.__host, self.__user, self.__password, self.__database)

      a = Mysql('192.168.1.12', 'user', 'user1234', 'test')
      a.prin() # output ('192.168.1.12', 'user', 'user1234', 'test')
      b = Mysql('192.168.1.132', 'admin', 'admin1234', 'train')
      b.prin() # output ('192.168.1.132', 'admin', 'admin1234', 'train')
      a.prin() # output ('192.168.1.132', 'admin', 'admin1234', 'train')
      ```





      share|improve this answer









      $endgroup$
















        0












        0








        0





        $begingroup$

        An error maybe happen when the number of date base is two or more in your project. Example as:



        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

        def prin(self):
        print(self.__host, self.__user, self.__password, self.__database)

        a = Mysql('192.168.1.12', 'user', 'user1234', 'test')
        a.prin() # output ('192.168.1.12', 'user', 'user1234', 'test')
        b = Mysql('192.168.1.132', 'admin', 'admin1234', 'train')
        b.prin() # output ('192.168.1.132', 'admin', 'admin1234', 'train')
        a.prin() # output ('192.168.1.132', 'admin', 'admin1234', 'train')
        ```





        share|improve this answer









        $endgroup$



        An error maybe happen when the number of date base is two or more in your project. Example as:



        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

        def prin(self):
        print(self.__host, self.__user, self.__password, self.__database)

        a = Mysql('192.168.1.12', 'user', 'user1234', 'test')
        a.prin() # output ('192.168.1.12', 'user', 'user1234', 'test')
        b = Mysql('192.168.1.132', 'admin', 'admin1234', 'train')
        b.prin() # output ('192.168.1.132', 'admin', 'admin1234', 'train')
        a.prin() # output ('192.168.1.132', 'admin', 'admin1234', 'train')
        ```






        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered 19 mins ago









        ning chenning chen

        84




        84






























            draft saved

            draft discarded




















































            Thanks for contributing an answer to Code Review Stack Exchange!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            Use MathJax to format equations. MathJax reference.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f39009%2fpython-connection-with-mysql%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Costa Masnaga

            Fotorealismo

            Sidney Franklin