我需要你帮助从List中获取值并将它们附加到insert语句中。我有一个名为Employee的课程:
public class Employee {
private Integer id; //Getter and Setter
private String name;//Getter and Setter
private String remarks;//Getter and Setter
private boolean disable;//Getter and Setter
public Employee(Integer id, String name, String remarks, boolean disable){
this.id = id;
this.name = name;
this.remarks=remarks;
this.disable=disable;
}
在bean中,我为employeeList生成随机数:
private List<Employee> employeeList;
private List<Employee> selectedEmployees;
public test() {
super();
employeeList = new ArrayList<Employee>();
for (int i = 1; i <= 10; i++) {
employeeList.add(new Employee(i, "Name " + i, "Remarks " + i, true));
}
}
所选值将存储在列表selectedEmployees
中。现在我想编写一个新方法来打印获取的值,然后将它们附加到insert语句以将选定的值插入表中。
public void updateRecords() {
System.out.println("Size =" + selectedEmployees.size());
//Here I need help to print the values of the list and then to append them to an insert statement to the table employees
insert into employees (id,name,remarks) values ();
}
答案 0 :(得分:0)
您可以使用for each
语句来达到此目的,但是因为您已声明了您的成员变量private
而无法阅读它们,因此您应该声明您的班级成员public
或声明getter读取成员数据
Connection connection = DriverManager.getConnection(...);
for(Employee e:selectedEmployees)
{
System.out.println("Employee id: "+e.id+" name: " + e.name+ " remarks: " + e.remarks);
String sql = "INSERT INTO employees (id,name,remarks) VALUES(?,?,?);";
PreparedStatement statement = connection.prepareStatement(sql);
statement.setInt(1, e.id);
statement.setString(2, e.name);
statement.setString(3, e.remarks);
statement.executeUpdate();
}
答案 1 :(得分:0)
对于arraylist,您将使用此语法。 X是列表中该员工的编号,那么您必须为变量创建getter和setter。
Employees.get(x).getName ();
然后,您将创建一个雇用对象,然后像这样插入。
Employee dude = new employee(1, name, remarks, disable);
Employees.add(dude);
答案 2 :(得分:0)
PreparedStatement#executeBatch是解决问题的最佳人选。
您可以像这样实现:
public void updateRecords(List<Employee> employees) {
System.out.println("Size =" + selectedEmployees.size());
//Here I need help to print the values of the list and then to append them to an insert statement to the table employees
String query = "insert into employees (id,name,remarks) values (?,?,?)";
Connection con = ... // establish DB connection
PreparedStatement ps = con.prepareStatement(query);
for(Employee emp : employees) {
ps.setNumber(1, emp.getId());
ps.setString(2, emp.getName());
ps.setString(3, emp.getRemarks());
ps.addBatch();
}
ps.executeBatch();
}
上面的代码只是一个示例,您需要将其编译为可编辑的,并且还需要进行适当的异常处理。
希望这有帮助。