jdbc链接数据库代码

package JDBC_1;

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

public class jdbcUtil {
    String driver = "com.mysql.jdbc.Driver";
    String url ="jdbc:mysql://127.0.0.1:3306/test";
    String username = "root";
    String password = "123";
    Connection conn = null;
    PreparedStatement ps = null;
    ResultSet rs = null;

    //获取连接的方法
    public Connection getConn() {
        try {
            Class.forName(driver);
            conn = DriverManager.getConnection(url,username,password);
        }catch (Exception e){
            e.printStackTrace();
        }
    return conn;
    }

    //通用的增删改
    public int excuteUP(String sql, Object []pp) {
        try {
            ps = getConn().prepareStatement(sql);
            if(pp != null){
                for (int i = 0; i<pp.length;i++){
                    ps.setObject(i+1,pp[i]);
                }
            }
            int result = ps.executeUpdate();
            return result;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;

    }


    //查询
    public ResultSet excuteSel(String sql,Object[] pp){
        try {
            ps = getConn().prepareStatement(sql);
            if (pp != null){
                for (int i = 0; i < pp.length; i++){
                    ps.setObject(i+1,pp[i]);
                }
            }
            rs = ps.executeQuery();
            this.closeAll(conn,ps,null);
        }catch (Exception e){
            e.printStackTrace();
        }

        return rs;
    }


    //关闭
    public void closeAll(Connection conn,PreparedStatement ps,ResultSet rs){
        try {
            if (rs != null){
                conn.close();
            }
            if (ps != null){
                rs.close();
            }
            if (conn != null){
                conn.close();
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

}



评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值