-2

i have a problem with syntax when i try send method post using python. This is my python function:

def insert_tipo_falla(self,cod_falla,desc_falla):
        sql = 'INSERT INTO TipoFallas(cod_tipo_falla,desc_falla) values ({},{})'.format(cod_falla,desc_falla)

        try:
            self.cursor.execute(sql)
            self.connection.commit()
        except Exception as e:
            raise
        finally:
            self.connection.close()

Sending with my API this json:

{
    "cod_tipo_falla":"104",
    "desc_falla":"TAP NIVELES BAJOS"
}

This function send a error when i try to insert with my API:

raise_mysql_exception raise errorclass(errno, errval) pymysql.err.ProgrammingError: (1064, "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 'NIVELES BAJOS)' at line 1")

I check several times, i insert manually way and it works, but using this python function dont it works Thanks and sorry for my english

Diego K.
  • 19
  • 4

2 Answers2

0

The issue is with the query that is formed and you could see the error if you try printing the query. You need to quote the text while inserting.

From :

sql = 'INSERT INTO TipoFallas(cod_tipo_falla,desc_falla) values ({},{})'.format(cod_falla,desc_falla)

To:

sql = 'INSERT INTO TipoFallas(cod_tipo_falla,desc_falla) values ({},"{}")'.format(cod_falla,desc_falla)
heretolearn
  • 6,047
  • 4
  • 29
  • 52
0

you can use placeholders instead

def insert_tipo_falla(self,cod_falla,desc_falla):
        sql = 'INSERT INTO TipoFallas(cod_tipo_falla,desc_falla) VALUES (%s,%s)'

        try:
            self.cursor.execute(sql,(cod_falla,desc_falla))
            self.connection.commit()
        except Exception as e:
            raise
        finally:
            self.connection.close()
nbk
  • 31,930
  • 6
  • 24
  • 40
  • 1
    i have similar code i visual studio code with the actual python 3.9.6, and it works fine and it follows the manual https://dev.mysql.com/doc/connector-python/en/connector-python-example-cursor-transaction.html – nbk Aug 13 '21 at 14:25
  • yeah, Apologies... i misread the code. This will work as expected. Will remove my earlier comment. – heretolearn Aug 13 '21 at 14:27