/**
* 查询 应用系统 各表的记录总数
*
* @param url 数据源地址
* @param userName 数据源登陆用户名
* @param password 数据源密码
* @param tableNames 表名 List
* @return Map < 表名,表下数据行数>
*/
static class CountThread implements Runnable{
CountThread(String tableName){
this.tableName=tableName;
}
static void setConnection(Connection connection) {
CountThread.connection = connection;
}
static void setReMap(ConcurrentHashMap map){
CountThread.reMap=map;
}
static void setThreadCount(CountDownLatch countDownLatch) {
CountThread.countDownLatch = countDownLatch;
}
private static CountDownLatch countDownLatch;
private static ConcurrentHashMap<String,String> reMap;
private static Connection connection;
private String tableName;
@Override
public void run() {
String sql = "SELECT COUNT(1) num FROM " + tableName;
System.out.println(sql);
try {
PreparedStatement stmt = connection.prepareStatement(sql);
ResultSet tablesRest = stmt.executeQuery();
while (tablesRest.next()) {
String count = tablesRest.getString("num");
reMap.put(tableName, count);
}
tablesRest.close();
tablesRest = null;
countDownLatch.countDown();
} catch (SQLException e) {
log.error(e.getMessage());
reMap.put(tableName, "0");
}
}
}
public static Map<String, String> conutRows(String url, String userName, String password, List<String> tableNames) {
int size=tableNames.size();
Date start=new Date();
ConcurrentHashMap<String, String> reMap = new ConcurrentHashMap<>(size);
CountDownLatch countDownLatch=new CountDownLatch(size);
try (Connection connection = DriverManager.getConnection(url, userName, password)) {
CountThread.setConnection(connection);
CountThread.setReMap(reMap);
CountThread.setThreadCount(countDownLatch);
for(String tableName:tableNames){
CountThread thread = new CountThread(tableName);
thread.run();
}
countDownLatch.await();
// sql.append(" SELECT ");
// for (String tableName : tableNames) {
// sql.append(" " + tableName + "b.num " + tableName + "a ,"); //字符串拼接 表名+a 拼接成表别名
// }
//
// //删除多余的一个 ,
// sql.deleteCharAt(sql.length() - 1);
// sql.append(" FROM ");
// //子查询 ,分别统计表字段数
// for (String tableName : tableNames) {
// sql.append(" ( SELECT COUNT(*) num FROM ");
// sql.append(tableName);
// sql.append(" ) " + tableName + "b ,");
// }
// //删除多余的一个 ,
// sql.deleteCharAt(sql.length() - 1);
// System.out.println(sql);
// //使用sql语句进行查询获取结果集
// PreparedStatement stmt = connection.prepareStatement(sql.toString());
// ResultSet tablesRest = stmt.executeQuery();
// //对结果进行遍历,此处结果集实际应只有一行数据
// while (tablesRest.next()) {
// for (String tableName : tableNames) {
// String count = tablesRest.getString(tableName + "a");
// reMap.put(tableName, count);
// }
// }
// tablesRest.close();
// tablesRest = null;
} catch (Exception e) {
log.error(e.getMessage());
throw new RuntimeException("数据源连接失败");
}
Date end=new Date();
long costTime = (end.getTime()-start.getTime());
System.out.println("******************************************"+costTime+"**************************");
return reMap;
}