java_JdbcUtilis_单实例

//eg1,没有使用单实例,eg2有

package cn.itcast;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement; public final class JdbcUtils { private static String url = "jdbc:mysql://localhost:/xxxx";
private static String user = "";
private static String password = ""; private JdbcUtils() {
} static {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
throw new ExceptionInInitializerError(e);
}
} public static Connection getConnection() throws SQLException {
return DriverManager.getConnection(url, user, 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();
}
}
}
}
}
上一篇:VS2008 Debug与Release的本质区别(转)


下一篇:[LeetCode] 033. Search in Rotated Sorted Array (Hard) (C++)