Error statement and executeUpdate SQL - NetBeans

1
try{
      Class.forName(driver);
      Connection conn = DriverManager.getConnection(str_conn, usuario, senha);
      Statement stmt = conn.createStatement();
      String sqlinsert ="insert into cheque (data_cheque,valor,repasse) values ("+
        jTextField1.getText()+","+
        jTextField2.getText()+",' "+
        jTextField3.getText()+" ') ";
      stmt.executeUpdate(sqlinsert);

      JOptionPane.showMessageDialog(null,"Sucesso");
    }
    catch (ClassNotFoundException ex) {
        System.out.println("Não foi possível carregar o driver.");
        ex.printStackTrace();
    }
    catch (SQLException ex) {
        System.out.println("Problema com o SQL");
        ex.printStackTrace();
    }
    
asked by anonymous 30.01.2015 / 18:30

1 answer

2

I believe the error is a% badly formatted%, values that are not numbers must be enclosed in single quotation marks. To use prepared statements change the values that are in the query by interrogation, and pass the values through the functions query sql , where PreparedStatement.set*(index, value) is the type of data to be exchanged.

Your query sql with the values would be printed like this:

insert into cheque (data_cheque,valor,repasse) values (2015-01-30, 100, 300')

If you were to apply it directly to the bank you should escape the non-numeric values with quotation marks, like this:

insert into cheque (data_cheque,valor,repasse) values ('2015-01-30', 100, 300)

With the prepared statement you avoid sql injection, tipa user entries and you also do not have to worry about escaping values.

 String sqlinsert ="insert into cheque (data_cheque,valor,repasse) values (?,?,?) ";
 PreparedStatement stmt = conn.prepareStatement(sqlinsert); 

 stmt.setDate(1,  jTextField1.getText());
 stmt.setInt(2,  jTextField1.getText());
 stmt.setInt(3,  jTextField1.getText());

 stmt.executeUpdate(sqlinsert);

List of setters corresponding to type - Oracle

    
30.01.2015 / 18:46