0

I have my database set up and I'm connected to it as I can add in values normally. I want to run a loop and add values now but I'm getting this error:

java.sql.SQLException: No value specified for parameter 1
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:996)
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:935)
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:924)
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:870)
    at com.mysql.jdbc.PreparedStatement.checkAllParametersSet(PreparedStatement.java:2281)
    at com.mysql.jdbc.PreparedStatement.fillSendPacket(PreparedStatement.java:2261)
    at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2120)
    at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2077)
    at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2062)
    at test.Test.main(Test.java:30)

Also, the first parameter in my table is an auto-increment value that's supposed to be set to NULL but Eclipse won't let me use NULL so any suggestions on that would be appreciated. Here is my code for adding the data:

Connection conn = null;
PreparedStatement pstmt = null;
int loopNumber = 0;
try {
    while (loopNumber < 10) {
        conn = getConnection();
        String query = "insert into username(id, name) values(?, ?)";

        pstmt = conn.prepareStatement(query); // create a statement
        pstmt.setInt(loopNumber, loopNumber); // set input parameter 1
        pstmt.setString(loopNumber, "deptname"); // set input parameter 2
        pstmt.executeUpdate(); // execute insert statement
    }
    loopNumber++;
} catch (Exception e) {
  e.printStackTrace();
} finally {
  pstmt.close();
  conn.close();
}

1 Answer 1

3

The first parameter of the setString/setInt method is the parameterIndex, which in your case can only be 1 or 2 (the first "?" and the second).

Therefore,

pstmt.setInt(loopNumber, loopNumber); // set input parameter 1
pstmt.setString(loopNumber, "deptname"); // set input parameter 2

Should become:

pstmt.setInt(1, loopNumber); // set input parameter 1
pstmt.setString(2, "deptname"); // set input parameter 2
Sign up to request clarification or add additional context in comments.

3 Comments

Regarding the auto-increment problem, there is a similar post here: stackoverflow.com/questions/17438288/…
Thanks alot! That solved it. Also thank you for linking the other question its very helpful.
If you still have problems using preparedStatement, just google it, there are a lot of good tutorials.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.