0

im reciveing this error upon trying to insert into table 'produto':

Traceback (most recent call last): File "C:\Python33\Archive\MySQL-teste12.py", line 278, in inserir(cursor, cx2) File "C:\Python33\Archive\MySQL-teste12.py", line 196, in inserir cursor.execute(add_produto) File "C:\Python33\lib\site-packages\mysql\connector\cursor.py", line 415, in execute self._handle_result(self._connection.cmd_query(stmt)) File "C:\Python33\lib\site-packages\mysql\connector\connection.py", line 593, in cmd_query result = self._handle_result(self._send_cmd(ServerCmd.QUERY, query)) File "C:\Python33\lib\site-packages\mysql\connector\connection.py", line 515, in _handle_result raise errors.get_exception(packet) mysql.connector.errors.ProgrammingError: 1054 (42S22): Unknown column 'dado' in 'field list'

Here is the table:

produto = """
     CREATE TABLE produto (
     prod_nu int(11) NOT NULL AUTO_INCREMENT,
     nome varchar(30) NOT NULL,
     data_lcm date NOT NULL,
     preco int(11) NOT NULL,
     PRIMARY KEY (prod_nu)
     ) ENGINE=InnoDB
     """

Here is the insertion procedure where the error occurs:

def inserir (cursor, db):
menu3 = 0
while menu3 != 99:
    print("""
----- Menu Banco MARK II, v.1.00, MySQL, VR -----

          ----- Menu de Inserção ----


1.Inserir em produto.
2.Inserir em cliente.
3.Inserir em empregado.
4.Inserir em salario.
99.Sair.

    """)
    menu3 = input("Digite sua Opção")

    if menu3 == '1':
        va = input("""

                   Digite o Nome do Produto.

                   """)

        vb = input("""

                   Digite a data de Lançamento do Produto (Ano/mês/dia).

                   """)
        input_date = datetime.strptime(vb, '%Y/%m/%d')

        vc = input("""

                   Digite o Preço do Produto (ex: 20, 20.33).

                   """)

        add_produto = """INSERT INTO produto(nome,
              data_lcm, preco)
              VALUES (%s, %s, %s)"""% (va, 'input_date', 'vc')

        #try:
        cursor.execute(add_produto)
        db.commit()
        print("""
              Inserção concluida com sucesso.

              """)
        #except:
         #   db.rollback()
          #  print("""

           #     Erro.

            #    """)
    if menu3 == '99':
        break

I tried adding * cursor.execute(*add_produto) but i recived a different error message. Also messed around with quotes in the insertion's values va and vc but only gave different error messages.

Thanks for any help.

1
  • Your description was "Unknown column 'data'". But your copy of the traceback says "Unknown column 'dado'". And meanwhile, neither one of those appears in your code. You have to give your actual code, and the actual errors you get, if you want people to debug things for you.
    – abarnert
    Oct 5, 2013 at 0:37

1 Answer 1

5

Never write code like this: code:

add_produto = """INSERT INTO produto(nome,
                 data_lcm, preco)
                 VALUES (%s, %s, %s)"""% (va, 'input_date', 'vc')

cursor.execute(add_produto)

Instead, do this:

add_produto = """INSERT INTO produto(nome,
                 data_lcm, preco)
                 VALUES (%s, %s, %s)"""

cursor.execute(add_produto, (va, input_date, vc))

Why?

Well, first, it sounds like your problem is figuring out how to convert between Python and SQL data types, quote and escape things properly, etc. The database engine already knows how to do that, so just let it do that for you.

On top of that, trying to do it yourself creates SQL injection opportunities.

And it makes it harder for the database to figure out how to cache and reuse compiled queries, because every time you do an insert, it's a different statement.

I tried adding * cursor.execute(*add_produto) but i recived a different error message.

Sure. add_produto is a string, so *add_produto is just going to pass each character of that string as a separate argument, which isn't going to do any good.

Also messed around with quotes in the insertion's values va and vc but only gave different error messages.

Just randomly changing things until they seem to work is a good way to write code that seems to work on one particular case, but doesn't work on any other case. It's not a good way to write code that actually works. If you ever find yourself messing around with "shotgun debugging" tactics like this, take a step back and ask yourself what's wrong with the string and why.

If you print out add_produto, you'll see that putting quotes around 'vc' doesn't put quotes around the value of the variable vc, it uses the literal string 'vc' instead of the value of the variable. So, it's not going to fix your problem.

2
  • It won't work if the number of arguments are more than 4. Saying: TypeError: execute() takes from 2 to 4 positional arguments but 12 were given
    – Deep
    Feb 9, 2019 at 21:01
  • 1
    it'll work if do coursor.execute like this: cursor.execute(sql_statement, (x, y))
    – RiseofRice
    Jan 8, 2020 at 16:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.