Statement and SQL Run Error - Netbeans

Asked

Viewed 610 times

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();
    }
  • What do you want to ask?

  • I have an error on the line "Statement stmt = Conn.createStatement();" and "stmt.executeUpdate(sqlinsert);" @Paulohdsousa

  • @Raphaelsantos Edit your question and add this information. Also add what error you get.

1 answer

2


I believe the mistake is a query sql badly formatted, values that are not numbers should be in single quotes. To use Prepared statements exchange the values in the query for queries, and pass the values through the functions PreparedStatement.set*(index, value), where the * is the type of die 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 inputs and also no need 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

Browser other questions tagged

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