加载基础数据到static,减少查询数据库次数
package com.?.util;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.naming.InitialContext;
import javax.sql.DataSource;
import org.apache.log4j.Logger;
public class Utility {
private static final Logger log = Logger.getLogger(Utility.class);
private static Map mpCityName; // 城市中文名称
private static Map mpCityCode;// 三字码
/** 获取中文城市名称 */
public static String getCityName(String code) {
if (code == null)
return code;
String cityName = "";
try {
cityName = (String) mpCityName.get(code.toUpperCase().trim());
} catch (Exception e) {
}
if (cityName == null)
return code;
else
return cityName;
}
public static void loadStaticData() {
Connection con = getConnection();
try {
Statement stmt = con.createStatement();
String sqlStr = "select code_f, name from city";
ResultSet rs = stmt.executeQuery(sqlStr);
mpCityName = new HashMap();
mpCityCode = new HashMap();
String cityName = "";
String cityCode = "";
while (rs.next()) {
cityCode = rs.getString(1).toUpperCase();
cityName = rs.getString(2);
mpCityName.put(cityCode, cityName);
mpCityCode.put(cityName, cityCode);
}
rs.close();
stmt.close();
con.close();
} catch (SQLException exp) {
Utility.logDBError(exp);
} catch (Exception ex) {
Utility.logError(ex);
}
}
/**
* 获取数据库连接
*/
public static Connection getConnection() {
try {
InitialContext initial = new InitialContext();
// 使连接池初始化
DataSource dataSource = (DataSource) initial
.lookup(Constants.JDBC_DATASOURCE_URL);
Connection con = dataSource.getConnection();
return con;
} catch (SQLException exp) {
logDBError(exp);
return null;
} catch (Exception ex) {
logError(ex);
return null;
}
}
/**
* 记录异常
*/
public static synchronized void logError(Exception exp) {
StackTraceElement ste[] = exp.getStackTrace();
StringBuffer content = new StringBuffer();
content.append("[" + exp.toString() + "]\n");
for (int i = 0; i < ste.length; i++) {
content.append(" " + ste[i].toString() + "\n");
}
log.error(content);
}
/**
* 记录数据库异常
*/
public static synchronized void logDBError(Exception exp) {
StackTraceElement ste[] = exp.getStackTrace();
StringBuffer content = new StringBuffer();
content.append(exp.toString());
for (int i = 0; i < ste.length; i++) {
content.append(" " + ste[i].toString() + "\n");
}
log.error(content);
}
/**
* 加载静态数据
*/
static {
try {
loadStaticData();
} catch (Exception ex) {
logError(ex);
}
}
}