简体   繁体   中英

Using a prepared statement with auto increment field

I am trying to do insert to a table whose primary key is set to auto increment using a prepared statement.

The fields in the table are as follows;

id, username, password, email, firstname, last name

My code is such that

    String sql = "INSERT INTO Users values (?,?,?,?,?, ?)";
    RegistrationStatus status = null;
    Connection conn = null;
    PreparedStatement st = null;
    try {
        conn = source.getConnection();
        st = conn.prepareStatement(sql);
        st.setString(2, username);
        st.setString(3, password);
        st.setString(4, email);
        st.setString(5, firstname);
        st.setString(6, lastname);
        st.executeUpdate();

Where i have read that we should no include the first item as the database will take care of it. This approach for me appears to be failing.

Would it be possible to get some help on how to solve this?

Change your statement to not include the id (or the exact name) column:

String sql = "INSERT INTO Users (username, password, email, firstname, lastname)"
    + " values (?,?,?,?,?)";
//...
st.setString(1, username);
st.setString(2, password);
st.setString(3, email);
st.setString(4, firstname);
st.setString(5, lastname);
//...

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