编写需求和描述:
1.需要一个数据库
2.本文是用单元测试的方式来实现增删改查
单元测试练习:
1.创建一个测试类
2.测试方法-a.增加功能
//增加用户
@Test
public void addUser() throws SQLException, ClassNotFoundException {
User user = new User();
user.setUsername("MingRen");
user.setPassword("MingRen123");
user.setNickname("鸣人");
String sql = "insert into user(username,password,nickname)values('"+user.getUsername()+"','"+user.getPassword()+"','"+user.getNickname()+"')";
//1.加载驱动
//2.创建连接 在工具类里面
Connection connection = JDBCUtils.getConnection();
//3.创建SQL操作对象
Statement statement = connection.createStatement();
//4.执行SQL语句
statement.executeUpdate(sql);
//5.释放资源
connection.close();
}
2.测试方法-b.删除功能
//删除用户
@Test
public void deleteUser() throws SQLException, ClassNotFoundException {
int id = 7;
String sql ="delete from user where id=" + id;
//1.加载驱动
//2.创建连接 在工具类里面
Connection connection = JDBCUtils.getConnection();
//3.创建SQL操作对象
Statement statement=connection.createStatement();
//4.执行SQL语句
statement.executeUpdate(sql);
//5.释放资源
connection.close();
}
2.测试方法-c.修改功能
//修改用户
@Test
public void updateUser() throws SQLException, ClassNotFoundException {
User user = new User();
user.setUsername("ZuoZhu");
user.setPassword("ZuoZhu456");
user.setNickname("佐助");
user.setId("7");
String sql = "update user set username ='"+user.getUsername()+"',password ='"+user.getPassword()+"',Nickname ='"+user.getNickname()+"'where id="+user.getId();
//1.加载驱动
//2.创建连接
Connection connection = JDBCUtils.getConnection();
//3.创建SQL操作对象
Statement statement = connection.createStatement();
//4.执行SQL语句
statement.executeUpdate(sql);
//5.释放资源
connection.close();
}
2.测试方法-d.id查询功能
//id查询
@Test
public void findById() throws SQLException, ClassNotFoundException {
int id = 7;
String sql = "select * from user where id ="+ id;
//1.加载驱动
//2.创建连接
Connection connection = JDBCUtils.getConnection();
//3.创建SQL操作对象
Statement statement = connection.createStatement();
//4.执行SQL语句
ResultSet resultSet = statement.executeQuery(sql);
while (resultSet.next()){
String ida = resultSet.getString("id");
String user = resultSet.getString("username");
String pass = resultSet.getString( "password");
String nickname = resultSet.getString("nickname");
System.out.println("id=" + ida+" username=" + user+" pass=" + pass + " nickname=" + nickname);
}
//5.释放资源
connection.close();
}
2.测试方法-e.全部查询功能
//全部查询
@Test
public void findAll() throws SQLException, ClassNotFoundException {
String sql = "select * from user";
//1.加载驱动
//2.创建连接
Connection connection = JDBCUtils.getConnection();
//3.创建SQL操作对象
Statement statement = connection.createStatement();
//4.执行SQL语句
ResultSet resultSet = statement.executeQuery(sql);
while (resultSet.next()){
String ida = resultSet.getString("id");
String user = resultSet.getString("username");
String pass = resultSet.getString("password");
String nickname = resultSet.getString("nickname");
System.out.println("id=" + ida+" username=" + user+" pass=" + pass + " nickname=" + nickname);
}
//5.释放资源
connection.close();
}