0
votes

I'm having difficulty with an update statement for MySQL in Python I've created a class for executing queries, all my other queries work but an update I could use a fresh pair of eyes.

database_handler.sql_post_query_with_args_performed_successfully("UPDATE members SET email ='[email protected]' WHERE id= '%s'",id) 

The function sql_post_query_with_args_performed_successfully returns true when it performs the query. As it stands this code is returning true but not updating the field of the table code for that is here: def sql_post_query_with_args_performed_successfully(self, query, args): with UseDatabase(self.MYSQL_DETAILS) as cursor: try: cursor.execute(query, args) return True except mysql.connector.errors.IntegrityError: return False

this function makes use of "UseDatabase" another class whichs handles the connection and execution of the queries, here id the code for that:

import mysql.connector

class UseDatabase:
    def __init__(self, configuration:dict):
        self.config = configuration

    def __enter__(self) -> 'cursor':
        """Connect to database and create a DB cursor. 

        Return the database cursor to the context manager.
        """        
        self.conn = mysql.connector.connect(**self.config)
        self.cursor = self.conn.cursor()
        return self.cursor

    def __exit__(self, exc_type, exc_value, exc_traceback):
        self.cursor.close()
        self.conn.commit()
        self.conn.close()
2
UPDATE members SET email ='[email protected]' WHERE id= %s Try to remove ' - Lukasz Szozda
perhaps commit or autocommit - Drew
when I remove the ' I get the following error: mysql.connector.errors.ProgrammingError: 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '%s' at line 1 - David_D
@Drew This is the code for the function def sql_post_query_with_args_performed_successfully(self, query, args): with UseDatabase(self.MYSQL_DETAILS) as cursor: try: cursor.execute(query, args) return True except mysql.connector.errors.IntegrityError: return False - David_D
take a peek at stackoverflow.com/q/384228 - Drew

2 Answers

0
votes

After more digging I realised my sql statement needed to be: "UPDATE members SET verified = 1 WHERE id = %s"

My function call required the id to be passed within a tuple like so: sql_post_query_with_args_performed_successfully("UPDATE members SET email ='[email protected]' WHERE id= %s",(id,))

-1
votes

After much trial and error I found the answer here: Python mysql.connector.errors. %s passed to SQL query with quotes

the statement being: "UPDATE members SET email='[email protected]' WHERE id='{0}'".format(id))