BaseDao模板

#if (${PACKAGE_NAME} && ${PACKAGE_NAME} != "")package ${PACKAGE_NAME};#end
#parse("File Header.java")
import java.sql.*;

public class BaseDao {
    private String driver = "com.mysql.cj.jdbc.Driver";
    private String url = "jdbc:mysql://localhost:3306/${database}?serverTimezone=Asia/Shanghai";
    private String user = "${user}";
    private String pwd = "${password}";
    public Connection conn = null;
    public PreparedStatement pstmt = null;
    public ResultSet rs=null;

    //获取连接
    public Connection getConnection() {
        try {
            //如果你没有conn 或者 conn是关闭的时候 就重新获取
            if (conn == null || conn.isClosed()) {
                //1.加载驱动
                Class.forName(driver);
                //2.创建conn
                conn = DriverManager.getConnection(url, user, pwd);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return conn;
    }

    //关闭所有连接
    public void closeAll(ResultSet rs, PreparedStatement pstmt, Connection conn) {
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        if (pstmt != null) {
            try {
                pstmt.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
    }

    public int executeUpdate(String sql, Object...objects){
        try {
            conn=getConnection();
            pstmt=conn.prepareStatement(sql);
            if (objects!=null){
                for (int i = 0; i < objects.length; i++) {
                    pstmt.setObject(i+1,objects[i]);
                }
            }
           return pstmt.executeUpdate();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally {
            closeAll(null,pstmt,conn);
        }
        return 0;
    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值