最好是使用一个工具类 ,把代码封装进去。- /**
- package cn.utils;
- import java.sql.Connection;
- /**
- * @author xiaodao
- *
- */
- public final class jdbcUtil {
- private String url = "jdbc:mysql://localhost:3306/jdbc";
- private String username = "root";
- private String password = "123456";
-
- private static jdbcUtil instance = null;
- private jdbcUtil(){}
-
- static{
- try {
- Class.forName("com.mysql.jdbc.Driver");
- } catch (ClassNotFoundException e) {
- throw new ExceptionInInitializerError();
- }
- }
- public static jdbcUtil getInstance(){
- if (instance == null) {
- synchronized (jdbcUtil.class) {
- if (instance == null) {
- instance = new jdbcUtil();
- }
- }
- }
- return instance;
- }
-
- public Connection getConnection() throws SQLException{
- return DriverManager.getConnection(url, username, password);
- }
- public static void free(ResultSet rs,Statement st,Connection conn) {
- try {
- if (rs != null) {
- rs.close();
- }
- }catch (Exception e) {
- e.printStackTrace();
- }
- finally{
- try {
- if (st != null) {
- st.close();
- }
- }catch (Exception e) {
- e.printStackTrace();
- }
- finally{
- try{
- if (conn != null) {
- conn.close();
- }
- }
- catch (Exception e) {
- e.printStackTrace();
- }
- }
- }
- }
- }
复制代码 |