1.jdbc中加载驱动时,我想放入静态代码中。以免多次加载,减少开销。但是我又希望可以用properties配置数据库信息,由于静态代码块是类加载的时候就执行,顺序上优先于构造函数。所以我将读取properties的过程放入构造函数中,抛异常。解决办法:申请静态的properties变量,将读取配置文件的过程也放入静态代码块中。
public class JdbcUtils {
private static Properties prop = null;
private JdbcUtils() {
}
static {
try {
prop = new Properties();
InputStream inStream = UserDaoFactory.class.getClassLoader()
.getResourceAsStream("dbconfig.properties");
prop.load(inStream);
Class.forName(prop.getProperty("driverClassName"));
} catch (Throwable e) {
throw new ExceptionInInitializerError(e);
}
}
public static Connection getConnection() throws SQLException {
return DriverManager.getConnection(prop.getProperty("url"),
prop.getProperty("username"), prop.getProperty("password"));
}
public static void free(ResultSet rs, Statement st, Connection conn) {
try {
if (rs != null)
rs.close();
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (st != null)
st.close();
} catch (SQLException e) {
e.printStackTrace();
} finally {
if (conn != null)
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
}
2. 应用完成后,jdbc在application下测试增删改查方法都没有问题。但是在tomcat服务器下一跑就抛 NoClassDefFoundError, 后来发现我的mysql-conn jar 是以第三方jar包导入的。而tomcat打包应用时,不会将第三方jar包一起打包,所以导致我的工具类JdbcUtils 无法构造。回忆老师视频中,才想起来,做web应用时,第三方jar包一定要放入WEB-INF下的lib中,之后eclipse就会自动导入web下。。。这个小问题,纠结了好长时间。。。mark一下。