如何将数据存储在从数据库中收集的对象数组中?

时间:2010-08-21 19:39:04

标签: java mysql jdbc pojo

在这里,我编码从DB获取数据。我想将数据存储在Object Array(POJO)中。 怎么做?这段代码也可以将数据插入数据库,但省略它。

import java.*;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class Jdbc {
static int id[] = new int[10];
static String name[] = new String[10];
static int salary[] = new int[10];
public static void main(String arg[])
{
    try {
          Statement stmt;
          ResultSet rs;
          Class.forName("com.mysql.jdbc.Driver");
          String url ="jdbc:mysql://localhost:3306/dwr";
          Connection con = DriverManager.getConnection(url,"root", "1234");
          System.out.println("URL: " + url);
          System.out.println("Connection: " + con);
          stmt = con.createStatement();
          System.out.println("Enter EmpId:");
          BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
          int empId=Integer.parseInt(br.readLine());
          System.out.println("Enter Name:");
          BufferedReader br1=new BufferedReader(new InputStreamReader(System.in));
          String name1=br1.readLine();
          System.out.println("Enter Salary:");
          BufferedReader br2=new BufferedReader(new InputStreamReader(System.in));
          int salary1=Integer.parseInt(br2.readLine());
          stmt.executeUpdate("INSERT INTO employee set EmpId='"+empId+"', Name='"+name1+"', salary='"+salary1+"';");
          stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);
          rs = stmt.executeQuery("SELECT * " + "from employee ORDER BY EmpId");
          System.out.println("Display all results:");
          int i = 0;
          while(rs.next()){
            id[i]= rs.getInt("Empid");
            name[i]= rs.getString("Name");
            salary[i]= rs.getInt("Salary");
            System.out.println("\n EmpId " + id[i]+ "\n name " + name[i] + "\n salary " + salary[i]);
          }

    }catch( Exception e ) {
          e.printStackTrace();
}
    Jdbc pojo = new Jdbc();

}
}

1 个答案:

答案 0 :(得分:2)

您可以使用提供的get方法一次填充一个对象的字段,因此如果您有一个名为employee的对象,它接受3个参数(id,name和salary),那么可以有这样的东西:

List<Employee> employee = new ArrayList<Employee>();
while(rs.next())
{
employee.add(new Employee(rs.getInt("Empid"), rs.getString("Name"),rs.getInt("Salary"));
}

否则,您可以使用ORM工具,例如Hibernate,并使用它来检索所显示的对象here

P.S。我提供的Java代码更像是伪代码。我还没有测试过。