简体   繁体   中英

Eclipse Inserting Data into MySQL with a while loop no value specified error

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();
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM