比较高效的获取mysql某张表的最大主键ID
借鉴ucenter中的写法

public void testMysql() {
String sql ="show create table uc_members";
String str;
try {
Class.forName(
"org.gjt.mm.mysql.Driver");
String url =
"jdbc:mysql://localhost:3306/tc_passport?autoReconnect=true&characterEncoding=UTF-8";
String user =
"root";
String password =
"123456";
Connection conn = DriverManager.getConnection(url, user, password);
Statement stmt = conn.createStatement();
//900 515

ResultSet _rs = stmt.executeQuery(sql);
while(_rs.next()) {
Blob blob = _rs.getBlob(2);
InputStream in =blob.getBinaryStream();
byte[] b = new byte[(int)blob.length()];
//开辟文件大小的空间
int len = 0;
int temp = 0;
while((temp = in.read()) != -1)
{
b[len] = (byte)temp;
len++;
}

in.close();
str = new String(b,0,len);
System.out.println(
"读取到的字符串为:"+str);

getMaxId(str);

}
_rs.close();
stmt.close();
conn.close();

} catch (Exception e) {
}


}

private void getMaxId(String str) {
Pattern p = Pattern.compile(
"(?i)aUTO_INCREMENT=(\\d+?)[\\s|$]",Pattern.CASE_INSENSITIVE);
Matcher m = p.matcher(str);
while(m.find()) {
System.out.println(
"--------maxId:"+(Integer.parseInt(m.group(1))-1));
}
}




lunzi   2011-07-16 15:52:47 评论:0   阅读:1601   引用:0

发表评论>>

署名发表(评论可管理,不必输入下面的姓名)

姓名:

主题:

内容: 最少15个,最长1000个字符

验证码: (如不清楚,请刷新)

Copyright@2004-2010 powered by YuLog