I am getting disturbing errors due to issues on primary keys and inserting values to table part of my code is here….
In the table I have 3 columns userName, userPwd and userId(auto_incremented primary key)
public boolean addUserBean(UserBean ub)
{
Connection conn = null;
PreparedStatement prepar = null;
boolean flag = false;
String sql = "insert into admin values(?,?)";
if (hasUser(ub.getUserName()))
{
return false;
}
try
{
prepar = conn.prepareStatement(sql,prepar.RETURN_GENERATED_KEYS);
prepar.setString(1, ub.getUserName());
prepar.setString(2, ub.getUserPwd());
int result = prepar.executeUpdate();
if (result > 0)
{
flag = true;
}
else
{
flag = false;
}
}
catch (Exception ex)
{
ex.printStackTrace();
}finally{
if (prepar != null) {
try {
prepar.close();
} catch (SQLException logOrIgnore) {
}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException logOrIgnore) {
}
}
}
return flag;
}
You should not be manually inserting values into auto increment field. Just leave it out of insert query alltogether.
the correct auto incremented value will be insseted automatically.
Added after more details from OP:
if MySQL complains that Field ‘userId’ doesn’t have a default value then what you told us about your table is wrong, and column userId is not in fact defined as auto increment