2016-04-23 100 views
-1

我需要您的幫助來從列表中獲取值並將它們附加到插入語句。我有一個類中調用員工說:如何從java列表獲取值

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; 
    } 

在豆,我生成隨機數的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。現在我想編寫一個新的方法來打印提取的值,然後將它們附加到一個插入語句中以將選定的值插入到表中。

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

可以使用for each語句來達到這個,但是因爲你已經宣佈你的成員變量private您無法讀取它們這樣無論是你應聲明你的類成員public或宣佈干將閱讀會員資料

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(); 
} 
+0

邀請SQL注入 – Sanjeev

+0

@Sanjeev謝謝你的注意事項 – Pooya

0

對於arraylist,您可以使用此語法。 X是列表中該員工的數量,那麼您將不得不爲您的變量創建getter和setter。

Employees.get(x).getName(); 

然後,您將創建一個聘用對象,然後像這樣插入。

Employee dude = new employee(1, name, remarks, disable); 

    Employees.add(dude); 
+0

這個解決方案與已經提出的問題無關,請仔細閱讀 – Pooya

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(); 

} 

上面的代碼只是你需要使它編譯,也需要做適當的異常處理的例子。

希望這會有所幫助。