java的web应用中页面上处理外键

这是我学到的一个处理页面上外键的一种不错的方法,现在和大家分享一下希望大家提出意见共同进步。

 

public static void createJS(Object entity) {
BasicDataSource dataSource = new BasicDataSource();
dataSource.setUrl("jdbc:mysql://localhost");
dataSource.setPassword("root");
dataSource.setUsername("root");
dataSource.setDriverClassName("com.mysql.jdbc.Driver");

QueryRunner queryRunner = new QueryRunner(dataSource);
StringBuffer sql = new StringBuffer();
sql.append("SELECT * FROM ");
String tableName = "";
try {
Field field = entity.getClass().getDeclaredField("TABLE_NAME");
field.setAccessible(true);
tableName = (String)field.get(entity);
} catch (SecurityException e) {
e.printStackTrace();
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
sql.append( tableName );
System.out.println(sql.toString());
List<Map<String,Object>> list = null;
try {
list = (List)queryRunner.query(sql.toString(), new MapListHandler());
} catch (SQLException e) {
e.printStackTrace();
}


StringBuffer jsSource = new StringBuffer();
jsSource.append("var ");
jsSource.append(tableName);
jsSource.append("Array");
jsSource.append(" = new Array();\n");

for (int i = 0; i < list.size(); i++) {
jsSource.append(tableName);
jsSource.append("Array[");
jsSource.append(list.get(i).get("id"));
jsSource.append("] = '");
jsSource.append(list.get(i).get("name"));
jsSource.append("';\n");
}
System.out.println(jsSource.toString());
FileOutputStream outPutStream;
try {
outPutStream = new FileOutputStream("E:\\web\\WebRoot\\js\\"+ tableName +".js");
IOUtils.write(jsSource.toString(), outPutStream, "utf-8");
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}

你可能感兴趣的:(java,sql,mysql,Web,jdbc)