'How to implement Junit testing for Insert operation using JDBC
I am totally 0 in JUnit also I am completely new to Java, here is the code for Insert operation in MySQL using JDBC,
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class InsertPStatementExample {
private static final String INSERT_USERS_SQL = "INSERT INTO newUsers" +
" (name, email, country, password) VALUES " +
" (?, ?, ?, ?);";
public static void main(String[] argv) throws SQLException {
InsertPStatementExample createTableExample = new InsertPStatementExample();
createTableExample.insertRecord();
}
public void insertRecord() throws SQLException {
System.out.println(INSERT_USERS_SQL);
// Step 1: Establishing a Connection
try (Connection connection = DriverManager
.getConnection("jdbc:mysql://localhost:3306/mysql_database", "root", "root");
// Step 2:Create a statement using connection object
PreparedStatement preparedStatement = connection.prepareStatement(INSERT_USERS_SQL,Statement.RETURN_GENERATED_KEYS)) {
// preparedStatement.setInt(1,autoGeneratedID);
preparedStatement.setString(1, "steve");
preparedStatement.setString(2, "[email protected]");
preparedStatement.setString(3, "AUS");
preparedStatement.setString(4, "simple");
System.out.println(preparedStatement);
// Step 3: Execute the query or update query
preparedStatement.executeUpdate();
ResultSet tableKeys = preparedStatement.getGeneratedKeys();
tableKeys.next();
int autoGeneratedID = tableKeys.getInt(1);
} catch (SQLException e) {
// print SQL exception information
printSQLException(e);
}
// Step 4: try-with-resource statement will auto close the connection.
}
public static void printSQLException(SQLException ex) {
for (Throwable e: ex) {
if (e instanceof SQLException) {
e.printStackTrace(System.err);
System.err.println("SQLState: " + ((SQLException) e).getSQLState());
System.err.println("Error Code: " + ((SQLException) e).getErrorCode());
System.err.println("Message: " + e.getMessage());
Throwable t = ex.getCause();
while (t != null) {
System.out.println("Cause: " + t);
t = t.getCause();
}
}
}
}
}
The code is working fine, but I need to implement JUnit testing for the insert operation for my given task, which I don't know how to do.
Can anyone help me on this to implement it?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
