Will Will - 2 months ago 6
Java Question

Number of columns for result set error in SQL database for Java app

I'm having an issue with adding data to a sql database through Java on Netbeans.

String bladeSerial;
String bladeType;
LocalTime startTime1;

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

Connection conn = null;
Statement st = null;
try {
conn = DriverManager.getConnection ("jdbc:derby://localhost:1527/db01", "Administrator", "admin"); //run procedure getConnection to connect to the database - see below
st = conn.createStatement(); //set up a statement st to enable you to send SQL statements to the database.
} catch (SQLException ex) {
Logger.getLogger(FormTwo1.class.getName()).log(Level.SEVERE, null, ex);
}

System.out.println ("Successful Connection");


String query = "insert into TB01(SERIAL,BLADETYPE,STARTT1) values ('+bladeSerial+', '+itemText+', '+(String.valueOf(startTime1))+')";
try (PreparedStatement pstmt = conn.prepareStatement(query)) {
pstmt.setString(1, bladeSerial);
pstmt.setString(2, bladeType);
pstmt.setString(3, String.valueOf(startTime1));
pstmt.executeUpdate();
} catch (SQLException ex) {
Logger.getLogger(FormTwo1.class.getName()).log(Level.SEVERE, null, ex);
}


I get the error
The column position '1' is out of range. The number of columns for this ResultSet is '0'.


In the database, Serial is
VARCHAR(5)
, Bladetype is
VARCHAR(80)
and StartT1 is
VARCHAR(12)


The startTime1 variable is saved in the format HH:mm:ss.SSS.

The database structure

I appreciate any help on this error

Answer

You need to give placeholder in your query. Change your code as given here...

String query = "insert into TB01(SERIAL,BLADETYPE,STARTT1) values (?, ?, ?)";
PreparedStatement pstmt = conn.prepareStatement(query);
pstmt.setString(1, bladeSerial);
pstmt.setString(2, bladeType);
pstmt.setString(3, String.valueOf(startTime1));
pstmt.executeUpdate();
Comments