Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

What is wrong with this code? I want to add values ​​to my Mysql database using raw input but I can not 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()

Thanks

share|improve this question
2  
"What is wrong with this code?" Erm, most everything. Please review additional tutorials. –  Ignacio Vazquez-Abrams yesterday

1 Answer 1

up vote 2 down vote accepted

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.

share|improve this answer
    
Thanks, it works!! –  wacg1987 yesterday
    
@user143543 You're welcome! –  cdonts yesterday

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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