JDBC增删改查操作

插入

@Test
public void demo01(){
//添加

Connection conn = null;
Statement st = null;
ResultSet rs = null;

try {
    //1 获得连接
    conn = JdbcUtils.getConnection();

    //操作
    //1) 获得语句执行者
    st = conn.createStatement();
    //2) 执行sql语句
    int r = st.executeUpdate("insert into category(cname) values('测试')");

    //3) 处理结果
    System.out.println(r);

} catch (Exception e) {
    throw new RuntimeException(e);
} finally{
    //释放资源
    JdbcUtils.closeResource(conn, st, rs);
}   

}

修改

@Test
public void demo02(){
//修改
Connection conn = null;
Statement st = null;
ResultSet rs = null;

try {
    conn = JdbcUtils.getConnection();

    st = conn.createStatement();
    int r = st.executeUpdate("update category set cname='测试2' where cid = 4");
    System.out.println(r);

} catch (Exception e) {
    throw new RuntimeException(e);
} finally{
    JdbcUtils.closeResource(conn, st, rs);
}

}

删除

@Test
public void demo03(){
//删除
Connection conn = null;
Statement st = null;
ResultSet rs = null;

try {
    conn = JdbcUtils.getConnection();

    //操作
    st = conn.createStatement();
    int r = st.executeUpdate("delete from category where cid = 4");
    System.out.println(r);

} catch (Exception e) {
    throw new RuntimeException(e);
} finally{
    JdbcUtils.closeResource(conn, st, rs);
}

}

通过id查询详情

@Test
public void demo04(){
//通过id查询详情
Connection conn = null;
Statement st = null;
ResultSet rs = null;

try {
    conn = JdbcUtils.getConnection();

    //操作
    st = conn.createStatement();
    rs = st.executeQuery("select * from category where cid = 30");
    //如果针对主键查询,使用if即可,因为最多只有一个数据
    if(rs.next()){
        String cid = rs.getString("cid");
        String cname = rs.getString("cname");
        System.out.println(cid + " @ " + cname );
    } else {
        System.out.println("没有数据");
    }

} catch (Exception e) {
    throw new RuntimeException(e);
} finally{
    JdbcUtils.closeResource(conn, st, rs);
}

}

查询所有

@Test
public void demo05(){
//查询所有
Connection conn = null;
Statement st = null;
ResultSet rs = null;

try {
    conn = JdbcUtils.getConnection();

    //操作
    st = conn.createStatement();
    rs = st.executeQuery("select * from category");

    while(rs.next()){
        String cid = rs.getString("cid");
        String cname = rs.getString("cname");
        System.out.println(cid + " @ " + cname );
    }

} catch (Exception e) {
    throw new RuntimeException(e);
} finally{
    JdbcUtils.closeResource(conn, st, rs);
}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值