在方法save()
中,我收到Employee的一个实例作为输入,我想将其添加到表employee
中,并返回这个添加的实例。我读到关于这个问题的文章,但没有找到问题的答案。
public Employee save(Employee employee) throws SQLException {
Connection connection = ConnectionSource.instance().createConnection();
String sql = "insert into employee VALUES(" +employee.getId() + ", " + "'employee.getFullName().getFirstName()'" + ", " +"'employee.getFullName().getLastName()'"+ ", " +"'employee.getFullName().getMiddleName()'"+ ", " + "'employee.getPosition()'" + ", " +"'employee.getHired()'"+ ", " + employee.getSalary()+ ", " +employee.getManagerId()+ ", " +employee.getDepartmentId() + ")";
connection.prepareStatement(sql);
PreparedStatement ps2 = connection.prepareStatement("select * from employee");
ResultSet resultSet = ps2.executeQuery();
resultSet.next();
Employee emp = new Employee(... );
return emp;
}
首先,最好不要使用这样的方法:
String sql = "insert into employee VALUES(" +employee.getId() + ", " + "'employee.getFullName().getFirstName()'" + ", " +"'employee.getFullName().getLastName()'"+ ", " +"'employee.getFullName().getMiddleName()'"+ ", " + "'employee.getPosition()'" + ", " +"'employee.getHired()'"+ ", " + employee.getSalary()+ ", " +employee.getManagerId()+ ", " +employee.getDepartmentId() + ")";
在这种情况下,可以进行sql注入。
而是使用
String sql = "insert into employee values (?, ?, ...)";
PreparedStatement statement = conn.prepareStatement(sql);
statement.setInt(1, employee.getId());
statement.setString(2, employee.getFullName().getFirstName());
...
对于你的问题,你可以尝试这样的方法:
public Employee save(Employee employee) throws SQLException {
try (Connection connection = ConnectionSource.instance().createConnection();;
PreparedStatement statement = connection.prepareStatement(SQL_INSERT,Statement.RETURN_GENERATED_KEYS);) {
statement.setInt(1, employee.getId());
statement.setString(2, employee.getFullName().getFirstName());
// ...
int affectedRows = statement.executeUpdate();
if (affectedRows == 0) {
throw new SQLException("Creating employee failed, no rows affected.");
}
try (ResultSet generatedKeys = statement.getGeneratedKeys()) {
if (generatedKeys.next()) {
employe.setId(generatedKeys.getLong(1));
}
else {
throw new SQLException("Creating employe failed, no ID obtained.");
}
}
return employee;
}
}