当前页面: 开发资料首页 → Java 专题 → 用Java实现自动在数据库表中生成ID号
摘要: 用Java实现自动在数据库表中生成ID号
/*
* 功能:增加字典信息时,自动生成最小的ID号码
* 参数:String 字典表名称 first 字典ID的首字母,代表唯一的字典
* 返回:String 生成的最小ID号码
*/
public String getId(String table, String first) {
// 所有除去首字母后的ID号码--整型,例如:11
int[] sid;
// 所有原始ID号码,例如:A11
String[] rid;
// 除去首字母后最小的ID号码--字符串
String sid_new = null;
// 程序返回的最小的原始ID号码
String rid_new = null;
// 循环参数
int i = 0;
int k = 0;
con = DatabaseConnection.getConnection("jdbc/wutie");
Statement stm = null;
ResultSet rst = null;
RowSet rowRst = null;
String sql = "SELECT * FROM " + table + " order by id";
try {
if (con.isClosed()) {
throw new IllegalStateException("error.sql.unexpected");
}
stm = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
rst = stm.executeQuery(sql);
while (rst.next()) {
k++;
}
sid = new int[k];
rid = new String[k];
rst = stm.executeQuery(sql);
// 如果不存在结果集,则直接在first字母后面加01,例如first="A",rid_new=A01
if (!rst.first()) {
rid_new = first.concat("01");
return rid_new;
}
// 如果存在结果集,则将表中所有ID号存入数组中,并转换为整型数据
else {
/*
while (rst.next()) {
rid[i] = rst.getString("id");
sid[i] = Integer.parseInt(rid[i].substring(1));
i++;
}
*/
for (rst.previous(); rst.next(); i++) {
rid[i] = rst.getString("id");
sid[i] = Integer.parseInt(rid[i].substring(1));
}
// 如果第一条记录ID号不为fisrt+01,例如A03、A05、A18等,则返回新增数据的ID号为A01
if (sid[0] != 1) {
rid_new = first.concat("01");
return rid_new;
}
// 如果第一条记录ID号为first+1,即A1,则执行下面语句
else {
// 如果总记录数只有一条,例如A1,则返回新增数据为A02
if (i == 1) {
rid_new = first.concat("02");
return rid_new;
}
else {
for (int j = 1; j < k; j++) {
// 如果相邻两条记录ID号的整数位相差1,则保存新增数据ID号整数位是前一位ID号整数位加1
if (sid[j] == sid[j-1] + 1) {
if (sid[j] < 9) {
sid_new = String.valueOf(sid[j] + 1);
rid_new = first.concat("0").concat(sid_new);
}
else {
sid_new = String.valueOf(sid[j] + 1);
rid_new = first.concat(sid_new);
}
}
// 如果相邻两条记录ID号的整数位相差非1,则返回新增数据ID号整数位是前一位ID号整数位加1
if (sid[j] != sid[j-1] + 1) {
if (sid[j-1] < 9) {
sid_new = String.valueOf(sid[j-1] + 1);
rid_new = first.concat("0").concat(sid_new);
return rid_new;
}
else {
sid_new = String.valueOf(sid[j-1] + 1);
rid_new = first.concat(sid_new);
return rid_new;
}
}
}
return rid_new;
}
}
}
}
catch (SQLException e) {
e.printStackTrace();
throw new RuntimeException("error.sql.runtime");
}
finally {
try {
stm.close();
con.close();
}
catch (SQLException e1) {
e1.printStackTrace();
throw new RuntimeException("error.sql.runtime");
}
}
}