JDBC数据库连接基类写法(BaseDao.java)

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * 数据库操作基类----负责数据库的连接与关闭,以及统一的方法
 * @author Administrator
 *
 */
public class baseDao {
    private static final String driver=" com.mysql.jdbc.Driver"; //数据库驱动字符串
    private static final String url= "jdbc:mysql://localhost:3306/pet_db"; //连接URL字符串
    private static final String user=" root"; //数据库用户名
    private static final String password=" 123456"; //数据库密码
    /**
    * 加载驱动文件(驱动文件只需要加载一次就行,不需要每次连接数据库都加载)
    */
    static { //static只运行一次,达到只加载一次的目的
        try {
            Class.forName(driver);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
    /**
    * 数据库连接
    */
    public Connection getConn(){
        Connection conn=null;
        try {
            conn=DriverManager.getConnection(url,user,password);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return conn;
    }
    /**
    * 关闭资源
    * @param conn
    * @param ps
    * @param rs
    */
    public void closeAll(Connection conn,Statement ps,ResultSet rs){
        try {
            if (rs!=null) {
                rs.close();
            }
            if (ps!=null) {
                ps.close();
            }
            if (conn!=null) {
                conn.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

     //增、删、改共用方法
    public int myExecuteUpdate(String sql,Object...objects){
        //Object...objects表示参数,有可能有,也可能没有,可能有1个,有可能有多个
        int result=0;
        Connection conn=null;
        PreparedStatement ps=null;
        try {
            conn=getConn(); //连接数据库
            ps=conn.prepareStatement(sql);
            //设置参数
            if (objects!=null&&objects.length>0) {
                for (int i = 0; i < objects.length; i++) {
                    ps.setObject((i+1), objects[i]);
                }
            }
            //返回结果
            result=ps.executeUpdate();
         } catch (Exception e) {
             e.printStackTrace();
        }
        finally{
            closeAll(conn, ps, null); //关闭资源
        }
        return result;
    }

}

你可能感兴趣的:(Java)