插入
@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);
}
}