jdbc编码模版和工具类的提取,增删改查代码体现

1:编写配置文件:
文件名:dbcfg.properties
driverClass=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/day17
user=root
password=sorry

2:释放资源工具类:
public class JdbcUtil {
 private static String driverClass;
 private static String url;
 private static String user;
 private static String password;
 static{
  //读取配置文件
  try {
   InputStream in = JdbcUtil.class.getClassLoader().getResourceAsStream("dbcfg.properties");
   Properties props = new Properties();
   props.load(in);
   driverClass = props.getProperty("driverClass");
   url = props.getProperty("url");
   user = props.getProperty("user");
   password = props.getProperty("password");
   Class.forName(driverClass);
  } catch (Exception e) {
   throw new ExceptionInInitializerError(e);
  }
 }
 
 public static Connection getConnection() throws Exception{
  Connection conn = DriverManager.getConnection(url,user,password);
  return conn;
 }
 public static void release(ResultSet rs,Statement stmt,Connection conn){
  if(rs!=null){
   try {
    rs.close();
   } catch (SQLException e) {
    e.printStackTrace();
   }
   rs = null;
  }
  if(stmt!=null){
   try {
    stmt.close();
   } catch (SQLException e) {
    e.printStackTrace();
   }
   stmt = null;
  }
  if(conn!=null){
   try {
    conn.close();
   } catch (SQLException e) {
    e.printStackTrace();
   }
   conn = null;
  }
 }
}
3:实体代码:
public class JdbcDemo4 {

 public static void main(String[] args) {
  Connection conn = null;
  Statement stmt = null;
  ResultSet rs = null;
  try {
   conn = JdbcUtil.getConnection();
   stmt = conn.createStatement();
   //...你的代码
  } catch (Exception e) {
   throw new RuntimeException(e);
  }finally{
   JdbcUtil.release(rs, stmt, conn);
  }
 }
}

jdbc增删改查:
public class JdbcDemo5 {
 @Test
 //增:
 public void testAdd(){
  Connection conn = null;
  Statement stmt = null;
  try{
   conn = JdbcUtil.getConnection();
   stmt = conn.createStatement();
   stmt.executeUpdate("insert into users (name,password,email,birthday) values('zhw','123','[email protected]','1989-09-06')");
  }catch(Exception e){
   throw new RuntimeException(e);
  }finally{
   JdbcUtil.release(null, stmt, conn);
  }
 }
 @Test
 //改
 public void testUpdate(){
  Connection conn = null;
  Statement stmt = null;
  try{
   conn = JdbcUtil.getConnection();
   stmt = conn.createStatement();
   stmt.executeUpdate("update users set password='111' where id=4");
  }catch(Exception e){
   throw new RuntimeException(e);
  }finally{
   JdbcUtil.release(null, stmt, conn);
  }
 }
 @Test
 //删
 public void testDel(){
  Connection conn = null;
  Statement stmt = null;
  try{
   conn = JdbcUtil.getConnection();
   stmt = conn.createStatement();
   stmt.executeUpdate("delete from users where id=4");
  }catch(Exception e){
   throw new RuntimeException(e);
  }finally{
   JdbcUtil.release(null, stmt, conn);
  }
 }
}

 

你可能感兴趣的:(jdbc编码模版和工具类的提取,增删改查代码体现)