Employees is an object listed in another class. It has the fields name, department, and experience. I use the main method to create a Swing object, take in any new employees, and call upon the addEmployees class.
What If I want to create more methods in this class that call to the database? Do I need to create a try/catch, set the variable 'connector', the whole process again?
What if I want to create a method in the same class that only sets the name and department? Do I need to add redundant code?
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 AddEmployees {
public String addEmployee(String name, String department, int experience){
Connection connector = null;
PreparedStatement stmt = null;
try {
Class.forName("com.mysql.jdbc.Driver");
// Load a connection to my DB
String url = "jdbc:mysql://localhost:3306/myjobsite";
connector = DriverManager.getConnection(url, "golden", "password");
String sql="INSERT INTO employees(name,department,experience) values(?,?,?)";
stmt = connector.prepareStatement(sql);
stmt.setString(1, name);
stmt.setString(2, department);
stmt.setInt(3, experience);
stmt.execute(); //run sql
} catch (SQLException e) {
// TODO Auto-generated catch block
return "Connection Failure";
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "Executed sql";
}
}
addEmployeesor any other database-access methods you write.