现在的位置: 首页 > 综合 > 正文

JDBC的封装

2018年05月26日 ⁄ 综合 ⁄ 共 2123字 ⁄ 字号 评论关闭

package com.tesjd;
import   java.sql.*;

//已测试过
public class DB {
//在使用时都要加载驱动所以放在静态代码块中
    static {
        try{
        Class.forName("com.mysql.jdbc.Driver");
        }catch(ClassNotFoundException e){
            e.printStackTrace();
        }
    }

    public static Connection getCon(){
        Connection con= null;
        
            try {
                con = DriverManager.getConnection("jdbc:mysql://localhost:3306/work?user=root&password=admin");

            } catch (SQLException e) {
                
                e.printStackTrace();
            }
        
        return con;
    }
    
    public static void closeCon(Connection con){
        try {

            if(con!=null){

             //有的可以有con = null,但我运行的时候出现了java.lang.NullPointException异常 所以注释了

                //con= null;  
                con.close();
            }
                
        }catch(SQLException e){
            e.printStackTrace();
        }
    }
    
    public static Statement getSta(Connection con){
        Statement sta= null;
         try {
             sta=con.createStatement();
         }catch(SQLException e){
             e.printStackTrace();
         }
         return sta;
    }
    
    public static PreparedStatement getPsta(Connection con,String sql){
        PreparedStatement psta= null;
        try {
            psta= con.prepareStatement(sql);
        }catch(SQLException e){
        e.printStackTrace();
        }
        return psta;
    }
    
    public static  void closeSta(Statement sta){
        try {
            if(sta!=null){
                //sta=null;
                sta.close() ;
            }
        }catch(SQLException e){
            e.printStackTrace();
        }
    }
    public static ResultSet  executeQuery (Statement sta, String sql)
    {
        ResultSet res= null;
        try {

            res= sta.executeQuery(sql);         

        }catch(Exception e){e.printStackTrace();

        return res;
    }
    
    public static void closeRes(ResultSet res){
        
        try{if(res!=null){
        //    res=null;   //不要乱写 只要这里写了null就会出现nullpoing错误
         res.close();
         }
        }catch(SQLException e){e.printStackTrace();}
        

    }

//重载上面的executeQuery()方法

    public  static ResultSet  executeQuery(Connection con,String sql){

        ResultSet res= null;
        try {
            res= con.createStatement().executeQuery(sql);
            
        }catch(SQLException e){e.printStackTrace();}
        return res;
    }
    
    
}

抱歉!评论已关闭.