第一步:加入junit依赖
<dependency>
<groupld>junit</groupld>
<artifactid>junit</artifactid>
<version>4.12</version>
<scope>text</scope>
</dependcency>
第二步:编写测试类
第三步:编写测试方法{
1.用户public修饰
2.无返回值类型:void
}
第四步:加入@test
案例——完成:添加、删除、修改、查询操作{
第一步:加载驱动
第二步:创建数据库连接
第三步:创建SQL操作对象
第四步:执行SQL语句
第五步:释放资源
}
案例1增加
private String url = "jdbc:mysql://localhost:3306/2207b";
private String username = "root";
private String passwrod = "123456";
@Test
public void addtext() throws ClassNotFoundException, SQLException {
User user = new User();
user.setId(24);
user.setName("qnind");
user.setPrice(13);
user.setShu(14);
String addsql = "insert into shang (id,name,price,shu) values ('" + user.getId() + "','" + user.getName() + "','" + user.getPrice() + "','" + user.getShu() + "')";
Class.forName("com.mysql.cj.jdbc.Driver");
Connection connection = DriverManager.getConnection(url, username, passwrod);
Statement statement = connection.createStatement();
statement.executeUpdate(addsql);
statement.close();
connection.close();
}
案例2删除
@Test
public void shantext() throws ClassNotFoundException, SQLException {
int id = 23;
String shansql = "delete from shang where id =" + id;
Class.forName("com.mysql.cj.jdbc.Driver");
Connection connection = DriverManager.getConnection(url, username, passwrod);
Statement statement = connection.createStatement();
statement.executeUpdate(shansql);
statement.close();
connection.close();
}
案例3修改
@Test
public void gaitext() throws ClassNotFoundException, SQLException {
User user = new User();
user.setId(22);
user.setName("q");
user.setPrice(13);
user.setShu(14);
String gaisql = "update shang set name ='" + user.getName() + "',price = '" + user.getPrice() + "',shu = '" + user.getShu() + "' where id = " + user.getId();
Class.forName("com.mysql.cj.jdbc.Driver");
Connection connection = DriverManager.getConnection(url, username, passwrod);
Statement statement = connection.createStatement();
statement.executeUpdate(gaisql);
statement.close();
connection.close();