简体   繁体   中英

Can't insert to mysql db with python

I'm trying to insert to my database but nothing happens, no errors nothing.

class:

class Database:

host = 'localhost'
user = 'root'
password = ''
db = 'quinielas'

def __init__(self):
    self.connection = MySQLdb.connect(self.host, self.user, self.password, self.db)
    self.connection.autocommit(True)
    self.cursor = self.connection.cursor()

def insert(self, query):
    try:
        self.cursor.execute(query)
        self.connection.commit() #metodo para acceptar actualizaciones

    except MySQLdb.Error:
        self.connection.rollback() #metodo para descartar actualizaciones


def query(self, query):
    cursor = self.connection.cursor( MySQLdb.cursors.DictCursor )
    cursor.execute(query)

    return cursor.fetchall()

def __del__(self):
    self.connection.close()

query:

db = Database()
query = "INSERT INTO jugadores (`name`, `r1`, `r2`, `r3`, `r4`," \
                " `r5`, `r6`, `r7`, `r8`, `r9`)" \
                " VALUES (%s, %d, %d, %d, %d, %d, %d, %d, %d, %d)"
db.insert(query .format(name, r1, r2, r3, r4, r5, r6, r7, r8, r9))

I'm using python 2.7 with the following lib: https://pypi.python.org/pypi/MySQL-python/1.2.5#downloads

First, you need to output a message in your except of try/catch to see the MySQL exception. Second your string interpolation is conflating the % operator and .format() method. The % operator uses %s (for strings) and %d (for numbers) whereas .format uses curly braces, {} , for any type placeholders. In building a concatenated string, you need to choose either version.

However in SQL, you should use neither when passing values into queries as you should bind them as parameters. In most Python-MySQL APIs, placeholders are %s which should NOT be confused with Python's % operator's string placeholder. As example, other RDMS's use the ? placeholder.

Consider adjusting your method in defined class, Database , to receive a tuple or list of parameters to be used in second, optional argument of cursor.execute(operation, params=None, multi=False) . Also, the proper string formatting is shown for exception message:

def insert(self, query, parameters):
    try:
        self.cursor.execute(query, parameters)
        self.connection.commit() #metodo para acceptar actualizaciones

    except MySQLdb.Error as e:
        print('MySQL error is: {}'.format(e))
        self.connection.rollback() #metodo para descartar actualizaciones

Then, adjust the call to pass a list of parameters with prepared statement that is not string formatted:

db = Database()
preparedstmt = "INSERT INTO jugadores (`name`, `r1`, `r2`, `r3`, `r4`," \
                " `r5`, `r6`, `r7`, `r8`, `r9`)" \
                " VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s)"
params_tuple = (name, r1, r2, r3, r4, r5, r6, r7, r8, r9)

db.insert(preparedstmt, params_tuple)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM