Search code examples
pythonpymysql

Parametrize insert Python pymysql


I have the following block of code

def write_metadata(self):
    try:
        with self.sql_writer.cursor as cursor:
            for data in self.input_data:
                sql = ("""INSERT INTO Sample (SampleName, TransferStatus, ClientSid, ClientSubjectId, ClientName, ProjectId, ProjectName, ExecutionId, Deleted)
                    VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s""")
                package_data = (data.sample_name, 0, 'client_sid', "Testing", data.client_name, data.project_id, data.project_name, '12345', '0')
                cursor.execute(sql, package_data)
            self.sql_writer.conn.commit()
    finally:
       self.sql_writer.conn.close()

the error that I am getting is

"errorMessage": "(1064, u\"You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 1\")"

Is there an issue with my parametrize of the sql? Is the issue because some of the values are numbers and %s is for string? Is the issue because some of the values are None?

Thanks.


Solution

  • You are missing a close paren ) at the end of your VALUES().

    You are also using a multi-line string incorrectly. Try this:

    sql = """INSERT INTO Sample (SampleName, TransferStatus, ClientSid, ClientSubjectId, ClientName, ProjectId, ProjectName, ExecutionId, Deleted)
              VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s)"""