使用junit测试JDBC时候数据库会插入两条数据
再使用Junit进行测试的时候,数据库插入语句会执行两次,插入进数据库两条语句,但是日志显示就执行了一遍
junit版本用的是4.4,更换了最新版本5.6.0-M1后就正常了
目录结构如下
pom.xml导入的依赖
<!--导入依赖-->
<dependencies>
<!--mysql驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
<!--junit-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.4</version>
</dependency>
</dependencies>
实体类User.java
public class User {
private int id;
private String name;
private String password;
}
UserDao.java
public class UserDao {
//配置信息
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost:3306/mybatis?useSSL=true&useUnicode=true&characterEncoding=UTF-8";
String username = "root";
String password = "root";
public int insertUser(User user) throws ClassNotFoundException, SQLException {
Class.forName(driver);
Connection connection = DriverManager.getConnection(url, username, password);
Statement statement = connection.createStatement();
String sql = "insert into mybatis.user(id, name, password) values (" + user.getId() + "," + user.getName() + "," + user.getPassword() + ")";
int i = statement.executeUpdate(sql);
statement.close();
connection.close();
return i;
}
}
测试文件UserDaoTest.java
public class UserDaoTest {
@Test
public void insertUserTest() throws SQLException, ClassNotFoundException {
UserDao userDao = new UserDao();
int i = userDao.insertUser(new User(20, "1234", "123456"));
System.out.println(i);
}
}
sql文件
create table user
(
id int(20) null,
name varchar(30) null,
password varchar(30) null
);