我正在尝试执行代码来为包含今天日期和连接的计数器的 sql 中的记录生成 id。问题是当我尝试点击生成按钮时,id 会生成当前日期,但我希望计数器在第二天或日期更改时重新初始化为 1,这在没有初始化的情况下请帮助。
import java.sql.ResultSet;
import java.text.SimpleDateFormat;
import java.util.Date;
public class MyCalendarUtil {
private static String buffer = "";
private static int counter = 1;
public String nextID() {
final String datePrefix = new SimpleDateFormat("yyyyMMdd").format(new Date());
if (Long.parseLong(returnMaxId()) > 0) {
MyCalendarUtil.counter = Integer.parseInt(returnMaxId().substring(8, returnMaxId().length()));
}
if (buffer.equals(datePrefix)) {
MyCalendarUtil.counter++;
} else {
MyCalendarUtil.buffer = datePrefix;
MyCalendarUtil.counter = 1;
}
String suffix = "";
if (MyCalendarUtil.counter <= 1000) {
if (validateRange(0, 9, MyCalendarUtil.counter)) {
suffix += "00" + counter;
} else if (validateRange(10, 99, MyCalendarUtil.counter)) {
suffix += "0" + counter;
} else if (validateRange(99, 999, MyCalendarUtil.counter)) {
suffix += counter;
}
}
return (datePrefix + suffix);
}
public boolean validateRange(int min, int max, int field) {
return field >= min && field <= max;
}
public String returnMaxId() {
String result = "";
try {
DBUtil util = new DBUtil();
Connection connection = util.getConnection();
ResultSet rs = connection.createStatement().executeQuery("SELECT MAX(id) AS 'lastId' FROM crap ");
if (rs.next()) {
result = (rs.getString(1) != null) ? rs.getString(1) : "0";
}
} catch (Exception e) {
e.printStackTrace();
System.out.println("Error : " + e.getMessage());
}
return result;
}
}