Consultation sql java

0

I'm programming with Java. I am new in this language. What happens is that I insert a table in MySQL, but it appears:

  

SQLException: Unknown column 'jose' in 'field list'

In fact, I printed the SQL and executed it in the PhpAdmin and it works. Do you know why this happens? Below I leave the code.

 private void btn_ingresarMouseClicked(java.awt.event.MouseEvent evt) {                                          
 /* Insumo obj= new Insumo();
obj.setDescripcion(txtrut.getText());
     JOptionPane.showMessageDialog(null, obj.getDescripcion());*/
String name=txtrut.getText();
String pass=jPasswordField1.getText();
String sql="INSERT INTO usuario values(1,"+name+","+pass+")";
  try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
 System.out.println("Registro exitoso");

} catch (Exception e) {

System.out.println(e.toString());

   }

    Connection con= null;

try {

      con = DriverManager.getConnection(
        "jdbc:mysql://localhost:3306/ropa_trabajo?"
        + "user=root&password=");

// Otros y operaciones sobre la base de datos...
 Statement sentencia=con.createStatement();
sentencia.executeUpdate(sql);
con.close();
    } catch (SQLException ex) {

// Mantener el control sobre el tipo de error
 System.out.println("SQLException: " + ex.getMessage());

}

    System.out.println(sql);
}                         
    
asked by jose miguel jara 31.12.2016 в 04:28
source

1 answer

1

The error happens because when you concatenate your variables directly to the SQL string:

String sql="INSERT INTO usuario values(1,"+name+","+pass+")";

... the resulting SQL does not include single quotes around the values. Probably, the insert results in something like:

INSERT INTO usuario values(1,jose,password)

Since jose is not surrounded by single quotes, MySQL assumes that jose is the name of a column.

Of course, you could add the missing quotes. But the real solution is to use PreparedStatement and use parameters.

Example:

String sql = "INSERT INTO usuario values(1,?,?)";
PreparedStatement sentencia = con.prepareStatement(sql);
sentencia.setString(1, name);
sentencia.setString(2, pass);
sentencia.executeUpdate();
    
answered by 31.12.2016 / 04:36
source