//添加用戶
public User add(User user) {
Connection con = null;
PreparedStatement stm = null;
ResultSet rs = null;
User info = null;
try{
// 與數據庫建立連接
con = JDBCUtils.getConnection();
//sql語句
String sql = "insert into user_info(username,password) value(?,?)";
stm=con.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
//填充占位符
stm.setString(1,user.getName());
stm.setString(2,user.getPassword());
stm.executeUpdate();
//獲取最后ID。
rs=stm.getGeneratedKeys();
//int n = stm.executeUpdate(); // 返回受影響的行數
if(rs.next()){
// 這里還要再實例化一次,找了幾個鍾啊,回憶總想哭
info = new User();
int id = rs.getInt(1);
info.setId(id);
return info;
}else{
return null;
}
}
catch (Exception exc){
exc.printStackTrace();
}
finally {
// 關閉資源
JDBCUtils.close(null,stm,con);
}
return null;
}
關鍵語句stm=con.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS); rs=stm.getGeneratedKeys();
設置增長起始值alter table 表名 AUTO_INCREMENT=1000; 這里設置起始值是1000
