前段时间用struts开发了一个b/s结构的信息管理系统,其中有一个功能是要求管理员能够对数据字典进行修改,数据字典的表结构基本上都是table(id, name),id为数据库其它表中所存储的内容,表示方式为a01、a02、a08、b10、b25、c12等等,一个字典就分配一个字母作为其id号的标识,其实就是为了调试时方便,在其它的表中判断该字典的名称。因此对于一个特定的字典表来说,其id号排序应该是a01、a02、a03、a04……
在对字典内容进行删除的时候并不需要考虑什么,直接使用delete语句就可以了。关键是添加字典信息时,管理员需要在表单中填写的是table中的name字段,id号如何生成就需要自己用代码来实现(包括id号的01号空缺,中间有断开等情况)。下面是我设计的代码,其中关键的地方都有详细的注释:
/* * 功能:增加字典信息时,自动生成最小的id号码 * 参数:string 字典表名称 first 字典id的首字母,代表唯一的字典 * 返回:string 生成的最小id号码 */public string getid(string table, string first) {// 所有除去首字母后的id号码--整型,例如:11int[] sid;
// 所有原始id号码,例如:a11string[] 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号整数位加1if (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");
}}}
注意:之所以生成a01而不是a1,是因为在sqlserver2000中根据id号正确排序的需要,如果按照升序排列,a1后面是a10、a11等,而不是a2。另外,在hibernate中有多种自动生成id字段的方法,但是这个项目比较小,我没有使用hibernate中间件,这里提供的只是生成字典id字段的一种简单思路,只能用于字典项不多于100项的情况,一般的情况可以满足了,但如果超过100项只需简单修改一下代码,不足之处还请大家多指教!
闽公网安备 35060202000074号