日期:2014-05-16 浏览次数:20578 次
import java.sql.*; import javax.sql.*; public final class JdbcUtil { /** * @param args */ private static String url = "jdbc:mysql://localhost:3306/jdbc"; // jdbc:mysql:///jdbc 本地默认端口可以省略 private static String user = "root"; private static String password = "123456"; private JdbcUtil() { } static { try { Class.forName("com.mysql.jdbc.Driver"); } catch (ClassNotFoundException e) { 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(); } } } } } }
static块用来注册驱动
getConnection函数用来获取连接
free函数用来安全的释放资源