4

Java知识点总结(JDBC-封装JDBC)

@(Java知识点总结)[Java, JDBC]

封装JDBC

  1. src目录下新建一个db.properties文件,用于封装数据库连接信息

clipboard.png

  1. 把获取数据库连接对象和关闭连接的操作封装到 DBUtil 这个类中
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
 
public class DBUtil {
  static Properties pros; //读取和处理资源文件的信息
  
  static{ // 只需要加载一次,所以写成静态代码块。执行本类时,加载
    pros = new Properties();
    try {
     pros.load(Thread.currentThread().getContextClassLoader()
         .getResourceAsStream("db.properties"));
    } catch (IOException e) {
     e.printStackTrace();
    }
  }
 
  public static Connection getConn(){
    Connection conn = null;
    try {
     Class. forName(pros.getProperty("mysqlDriver"));
     conn = DriverManager.getConnection(pros.getProperty("mysqlUrl"),
         pros.getProperty( "mysqlUser"), pros.getProperty("mysqlPassword"));
    } catch (ClassNotFoundException | SQLException e) {
     e.printStackTrace();
    }
    return conn;
  }
  
  // 不建议把conn写为静态的全局变量,然后在方法中关闭
  public static void close(Connection conn){
    try {
     conn.close();
    } catch (SQLException e) {
     e.printStackTrace();
    }
  }
  
  public static void close(Statement stmt) {
    try {
     stmt.close();
    } catch (SQLException e) {
     e.printStackTrace();
    }
  }
  
  public static void close(PreparedStatement pstmt) {
    if (pstmt != null) {
     try {
       pstmt.close();
     } catch (SQLException e) {
       e.printStackTrace();
     }
    }
  }
  
  public void close(ResultSet rs) {
    try {
     rs.close();
    } catch (SQLException e) {
     e.printStackTrace();
    }
  }
  
  public static void commit(Connection conn) {
    if (conn != null) {
     try {
       conn.commit();
     } catch (SQLException e) {
       e.printStackTrace();
     }
    }
  }
  
  public static void rollback(Connection conn) {
    if (conn != null) {
     try {
       conn.rollback();
     } catch (SQLException e) {
       e.printStackTrace();
     }
    }
  }
  
  public static void setAutoCommit(Connection conn, boolean autoCommit) {
    if (conn != null) {
     try {
       conn.setAutoCommit(autoCommit);
     } catch (SQLException e) {
       e.printStackTrace();
     }
    }
  }
  
  
  //连接测试
  public static void main(String[] args) {
    if (DBUtil.getConn()!=null) {
     System.out.println("连接成功!");
     
    }
  }
}

苏生
803 声望725 粉丝