如何使用hashmap或map编写相同的代码。这样我就可以在表中检索值..
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection("jdbc:Oracle:thin:@localhost:1521:IHDB","pummy","pummy");
PreparedStatement ps=con.prepareStatement("select workitemid,empname,salary from emp where product_id=? and operation_id=?");
ps.setInt(1,prod_id);
ps.setInt(2,opn_id);
ResultSet rs=ps.executeQuery();
System.out.println("ProdId: "+prod_id);
System.out.println(rs);
while(rs.next())
{
BigDecimal workitemid = rs.getBigDecimal(1);
String empname=(String) rs.getString(2);
int salary= rs.getInt(3);
}
答案 0 :(得分:0)
我认为结构化的方式是创建Employee pojo class
,如下所示 -
public class Employee{
public BigDecimal workitemid;
public String empName;
public int salary;
<getter & setter>
}
现在创建一个Map
- Map<BigDecimal,Employee> empMap = new HashMap<>();
while(rs.next()){
Employee emp = new Employee();
BigDecimal workitemid = rs.getBigDecimal(1);
emp.setWorkitemid(workitemid);
emp.setEmpName(rs.getString(2));
emp.setSalary(rs.getInt(3));
map.put(workitemid, emp);
}
答案 1 :(得分:0)
你有。
PreparedStatement ps=con.prepareStatement("select workitemid,empname,salary from emp where product_id=? and operation_id=?");
ps.setInt(1,prod_id);
ps.setInt(2,opn_id);
ResultSet rs=ps.executeQuery();
System.out.println("ProdId: "+prod_id);
Map<BigDecimal,Employee> empMap= new HashMap<BigDecimal,Employee>();
System.out.println(rs);
while(rs.next())
{
Employee emp = new Employee();
emp.setWorkItemId = rs.getBigDecimal(1);
emp.setEmpName(rs.getString(2));
emp.setSalary(rs.getInt(3));
empMap.put(emp.getWorkItemId,emp);
}
private class Employee{
private String empName;
private int salary;
private BigDecimal workItemId;
//getters and setters
}
答案 2 :(得分:0)
PreparedStatement ps=con.prepareStatement("select workitemid,empname,salary from emp where product_id=? and operation_id=?");
ps.setInt(1,prod_id);
ps.setInt(2,opn_id);
ResultSet rs=ps.executeQuery();
System.out.println("ProdId: "+prod_id);
System.out.println(rs);
Map<BigDecimal, Employee> employees = new HashMap<BigDecimal, Employee>();
while(rs.next())
{
BigDecimal workitemid = rs.getBigDecimal(1);
String empname=(String) rs.getString(2);
int salary= rs.getInt(3);
Employee employee = new Employee(workitemid, empname, salary);
employees.put(workitemid , employee);
}
//object to hold information about an employee and to be able to use a map.
public class Employee
{
private BigDecimal workitemid;
private String empName;
private int salary;
//constructor
public Employee(BigDecimal workitemid, String empName, int salary)
{
this.workitemid = workitemid;
this.empName = empName;
this.salary = salary;
}
//setters and getter methods for workitemid, empName, salary.
}