1

What is wrong with this code? I want to add values ​​to my Mysql database using raw input, but I can't do it. The program runs perfectly, but when I look into database in mysql none of the data was recorded.

import MySQLdb

# Establecemos la conexión con la base de datos
bd = MySQLdb.connect("localhost","wil","1234","caras" )

# Preparamos el cursor que nos va a ayudar a realizar las operaciones con la base de datos
cursor = bd.cursor()

# Preparamos el query SQL para insertar un registro en la BD

sql = "INSERT INTO PERSONAS USUARIO VALUES" + raw_input("USUARIO: ")
sql = "INSERT INTO PERSONAS CONTRASENHA VALUES" + raw_input("CONTRASENHA: ")
sql = "INSERT INTO PERSONAS NOMBRE VALUES raw_input" + raw_input("NOMBRE: ")
sql = "INSERT INTO PERSONAS APELLIDO VALUES raw_input" + raw_input("APELLIDO: ")
sql = "INSERT INTO PERSONAS EDAD VALUES raw_input" + raw_input("EDAD: ")
sql = "INSERT INTO PERSONAS SEXO VALUES raw_input" + raw_input("SEXO: ")
sql = "INSERT INTO PERSONAS SALARIO VALUES raw_input" + raw_input("SALARIO: ")

try:
   # Ejecutamos el comando
   cursor.execute(sql)
   # Efectuamos los cambios en la base de datos
   bd.commit()
except:
   # Si se genero algún error revertamos la operación
   bd.rollback()

# Nos desconectamos de la base de datos 
bd.close()
1
  • 2
    "What is wrong with this code?" Erm, most everything. Please review additional tutorials. Commented Aug 11, 2014 at 20:48

2 Answers 2

3

First, you're replacing the sql variable content in each assigment, so only the last query will be executed. I also guess this is what you're trying to do:

cursor.execute("INSERT INTO PERSONAS VALUES (%s, %s, %s, %s, %s, %s, %s)",
               (raw_input("USUARIO: "), raw_input("CONTRASENHA: "),
                raw_input("NOMBRE: "), raw_input("APELLIDO: "),
                raw_input("EDAD: "), raw_input("SEXO: "),
                raw_input("SALARIO: ")))

Hope this helps.

Sign up to request clarification or add additional context in comments.

Comments

0

Change "sql = " to "sql +=" from the second line and give ";" at end of all the statements. You are basically replacing all the query with the next one. Not adding to the string.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.