源地址:http://marsvaadin.iteye.com/blog/1465592
由于不想用正则表达式,发现另外的方法
修改代码:
/**
* 通过 mysql的 show create table TABLE_NAME逆向生成Bean;
*
* @param conn
* @param tname
* @param outputdir
* @param packname
*/
private void parseTableByShowCreate(Connection conn, String tablename, String packname, String outputdir) {
StringBuilder classInfo = new StringBuilder("\t/**\r\n\t*");
boolean shouldCloseConn = false;
// String sql = "show create table " + tablename;
String sql = "SHOW FULL FIELDS FROM " + tablename;
ResultSet rs = null;
try {
rs = DBManager.query(conn, sql);
StringBuilder fields = new StringBuilder();
StringBuilder methods = new StringBuilder();
int i = 0;
while (rs.next()) {
String fieldName = rs.getString("Field");
String fieldType = "";
if (rs.getString("Type").contains("(")) {
fieldType = typeTrans(rs.getString("Type").substring(0, rs.getString("Type").indexOf("(")));
} else {
fieldType = typeTrans(rs.getString("Type"));
}
String cmt = rs.getString("Comment");
fields.append(getFieldStr(fieldName, fieldType, cmt));
methods.append(getMethodStr(fieldName, fieldType));
if (i == 0) {
classInfo.append("此类由" + getClass().getSimpleName() + "工具自动生成\r\n");
classInfo.append("\r\n");
classInfo.append("\t*@author \r\n");
classInfo.append("\t*@since ");
classInfo.append(sdf.format(new Date()));
classInfo.append("\r\n\t*/\r\n\r\n");
}
i++;
}
classInfo.append("public class ").append(upperFirestChar(tablename)).append("{\r\n");
classInfo.append(fields);
classInfo.append(methods);
classInfo.append("\r\n");
classInfo.append("}");
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
DBManager.close(shouldCloseConn ? conn : null, null, rs);
}
String packageinfo = "package " + packname + ";\r\n\r\n";
File file = new File(outputdir, upperFirestChar(tablename) + ".java");
System.out.println(file.getAbsolutePath());
try {
FileWriter fw = new FileWriter(file);
fw.write(packageinfo);
fw.write(classInfo.toString());
fw.flush();
fw.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}