package com.tedu;
/**
*
*实现Jdbc的增(Create)删(Delete)改(Update)查(Retrieve)
*CRUD
*/
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import org.junit.Test;
import com.tedu.util.JdbcUtil;
public class TestJdbcCRUD {
//新增:往account表中添加一个名称为john、money为3500的记录
@Test
public void testInsert() {
Connection conn = null;
Statement stat = null;
ResultSet rs = null;
try {
//注册驱动获取连接
conn = JdbcUtil.getConn();
//获取传输器,执行sql并返回结果
stat = conn.createStatement();
String sql = "insert into account value(null,'john',3500)";
int rows = stat.executeUpdate(sql);
System.out.println("影响行数"+rows);
} catch (Exception e) {
e.printStackTrace();
}finally {
//释放资源
JdbcUtil.close(conn, stat, rs);
}
}
//修改:将account表中名称为john的记录,money修改为1500
@Test
public void testUpdate() {
Connection conn = null;
Statement stat = null;
try {
//注册驱动并获取连接
conn = JdbcUtil.getConn();
//获取传输器,执行sql返回结果
stat = conn.createStatement();
String sql = "update account set money = 1500 where name = 'john'";
int rows = stat.executeUpdate(sql);
System.out.println("影响行数"+rows);
} catch (Exception e) {
e.printStackTrace();
}finally {
JdbcUtil.close(conn, stat, null);
}
}
//查询:查询account表中名称为john的记录
@Test
public void testFindName() {
Connection conn = null;
Statement stat = null;
ResultSet rs = null;
try {
conn = JdbcUtil.getConn();
stat = conn.createStatement();
String sql = "select * from account where name = 'andy'";
rs = stat.executeQuery(sql);
while(rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
double money = rs.getDouble("money");
System.out.println(id+":"+name+":"+money);
}
} catch (Exception e) {
e.printStackTrace();
}finally {
JdbcUtil.close(conn, stat, rs);
}
}
//删除:删除account表中名称为john的记录
@Test
public void testDelete() {
Connection conn = null;
Statement stat = null;
try {
conn = JdbcUtil.getConn();
stat = conn.createStatement();
String sql = "delete from account where name = 'john'";
int rows = stat.executeUpdate(sql);
System.out.println(rows);
} catch (Exception e) {
e.printStackTrace();
}finally {
JdbcUtil.close(conn, stat, null);
}
}
}
Jdbc的增删改查
最新推荐文章于 2024-03-27 17:28:38 发布