0

I am trying to update our SQL database from a JFrame panel in Netbeans. Currently, I am trying to use a button in from the "registernewStudent" panel, where the user can assing 4 text fields, where the first (Student ID) and the last (room) should be an integer and the middle 2 are strings. However, I am getting an errormessage saying "Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException"

Below are the source code for the button.

This is our first real project, so we'd appreciate any help we could get.

private void btnNyREActionPerformed(java.awt.event.ActionEvent evt) {                                        
    try {
        String talStrang1 = txtElevID.getText();
        int tal1 = Integer.parseInt(talStrang1); 
        String Strang2 = txtElevFN.getText();
        String Strang3 = txtElevEN.getText();
        String talStrang4 = txtElevSS.getText(); 
        int tal2 = Integer.parseInt(talStrang4);

        database.insert("insert into Elev values( tal1, Strang2, Strang3,tal2)");

    } catch (InfException ex) {
        Logger.getLogger(NyRegElev.class.getName()).log(Level.SEVERE, null, ex);
    } 
}    
rjdkolb
  • 10,377
  • 11
  • 69
  • 89
hw17
  • 9
  • 2
  • 2
    Please learn how to use a `PreparedStatement`: http://docs.oracle.com/javase/tutorial/jdbc/basics/prepared.html –  May 12 '17 at 12:04

1 Answers1

3

For one, you need to specify which columns you want the values to be inserted into. Something like:

database.insert("insert into Elev (column1, column2, column3, column4) values...;

The column# would be the actual name of the column in the table.

Secondly, you can't just put variables into the SQL as a string. It will not detect them as a variable. Instead you need to use concatenation and do something like:

database.insert("insert into Elev (column1, column2, column3, column4) values(" + tal1 + "," + Strang2 + "," Strang3 + "," tal2 + ")";

But this leaves you open to vulnerabilities. You should instead use prepared statements to avoid SQL injections.

An example of a MySQL prepared statement in Java can be found in the above link. For an example, I've taken your query and converted the example to what it should look like for you:

String query = "insert into Elev (column1, column2, column3, column4) values (?, ?, ?, ?)";

// create the mysql insert preparedstatement
      PreparedStatement preparedStmt = conn.prepareStatement(query);
      preparedStmt.setInt(1, tal1);
      preparedStmt.setString (2, Strang1);
      preparedStmt.setString (3, Strang3);
      preparedStmt.setInt(4, tal2);

// execute the preparedstatement
      preparedStmt.execute();

The prepared statement will take the parameters supplied and put them in place of the ?'s that are in the query variable (among other things).

rjdkolb
  • 10,377
  • 11
  • 69
  • 89
Timothy G.
  • 6,335
  • 7
  • 30
  • 46