Evan12
Evan12

Reputation: 19

java derby database query, with user input text

I have a java derby database, I can write to and read from the database.

I am having trouble:

Making it so that the text that the user enters into the text field, is then incorporated into the database query to determine the results displayed.

I tried it this way, the results were, if I click the search button, it will return the info/query into the "run" screen, not actually incorporating the user input into the query tho, I have to do that in the code, by replacing the abc to the number in the database.

Do I have to create some kind of command line argument? set the variable differently? Can I just replace the query info where the database info goes with a variable like how I tried in the upcoming example?

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {  

    String abc = jTextField1.getText();
    String data = "jdbc:derby://localhost:1527/sample";
    try (
        Connection conn = DriverManager.getConnection(
          data, "app", "app");
        Statement st = conn.createStatement())   { 
            Class.forName("org.apache.derby.jdbc.ClientDriver");
            ResultSet rec = st.executeQuery(
              "select ROW1, ROW2, ROW3, ROW4, ROW5 from APP.NAME1 "
                      + "where (ROW4 = 'abc')");
        while (rec.next())  {
            System.out.println("ROW1:\t"
          + rec.getString(1));
            System.out.println("ROW2:\t"  + rec.getString(2));
            System.out.println("ROW3:\t"  + rec.getString(3));
            System.out.println("ROW4:\t" + rec.getString(4));
            System.out.println("ROW5:\t"  + rec.getString(5));
            System.out.println();
        }
        st.close();

    } catch (SQLException s)  {
        System.out.println("SQL Error: " + s.toString()  + " "
              + s.getErrorCode() + " " + s.getSQLState());
    } catch (Exception e) {
        System.out.println("Error: " + e.toString()
      + e.getMessage());
    }                                        
}
private void jTextField1ActionPerformed(java.awt.event.ActionEvent evt) {                                            

}

Upvotes: 1

Views: 878

Answers (1)

Deendayal Garg
Deendayal Garg

Reputation: 5148

You are not setting the variable correctly. Instead of setting the ROW4 to 'abc' you need to set the variable. Try this.

"select ROW1, ROW2, ROW3, ROW4, ROW5 from APP.NAME1 " + "where (ROW4 = '"+abc+"')"

Its always better to use preparedStatement. this will avoid lot of problem related to SQL Injection.

String selectSQL = "select ROW1, ROW2, ROW3, ROW4, ROW5 from APP.NAME1 where ROW4 = ?";
PreparedStatement preparedStatement = dbConnection.prepareStatement(selectSQL);
preparedStatement.setString(1, abc);
ResultSet rs = preparedStatement.executeQuery(selectSQL );

Upvotes: 1

Related Questions