pass input data to mysql database table

Asked

Viewed 253 times

2

People help me there, I’m creating a user manager with level system. however I am not able to pass a value of the variable defined by input() to the INSERT. please help me.

code:

def registrar_usuario():

    print("id:")
    id_bd = input()

    print("level:")
    level_bd = input()

    print("usuario:")
    usuario_bd = input()

    print("senha:")
    senha_bd = input()

    criar_usuarios = " INSERT INTO `usuarios` (`id`, `level`, `usuario`, `senha`) VALUES(%s,%s,%s,%s) (id_bd, level_bd, usuario_bd, senha_bd) "
    banco_de_dados.execute(criar_usuarios)
  • Hello Ghost Designer, what is the error message that returns?

  • Essa aqui amigo: mysql.connector.errors.Programmingerror: 1064 (42000): 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 '%s,%s,%s,%s,%s) (id_bd, level_bd, usuario_bd, senha_bd)' at line 1

  • 1

    Try this way: crea_usuarios = "INSERT INTO usuarios ('id', 'level', 'user', 'password') VALUES(%s,%s,%s,%s) (id_bd, level_bd, usuario_bd, senha_bd)"

  • Not the same error occurred.

  • Hello Ghost, I tested the code of my answer here and it worked right. Tip: Create a file called teste_insert.py and paste the code of my answer. To make it work I used the XAMP and Mysql connector. In XAMP you create a bank equal to my answer. In "user" you put root and the password leaves blank. Doing this will work, then just adapt the code to do what you need. Hug!

  • https://dev.mysql.com/downloads/connector/python/

Show 1 more comment

1 answer

2


In your INSERT has an extra space at the beginning of the string. In the table name there should be no quotes. In addition you are using crase where should be single quotes. See this example and compare!

import mysql.connector

mydb = mysql.connector.connect(
  host="localhost",
  user="yourusername",
  passwd="yourpassword",
  database="mydatabase"
)

mycursor = mydb.cursor()

sql = "INSERT INTO customers (name, address) VALUES (%s, %s)"
val = ("John", "Highway 21")
mycursor.execute(sql, val)

mydb.commit()

print(mycursor.rowcount, "record inserted.")

Browser other questions tagged

You are not signed in. Login or sign up in order to post.