gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 09:17:48 24 4
gpt4 key购买 nike

在这里,我已经编码以从数据库获取数据。我想将数据存储在对象数组(POJO)中。怎么做?这段代码也可以将数据插入DB,但是省略了。

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

}
}

最佳答案

您可以使用提供的 get 方法一次填充对象的字段,因此,如果您有一个名为雇员的对象,它接受 3 个参数(id、姓名和薪水) ),你可以有这样的东西:

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 所示

附注我提供的 Java 代码更像是伪代码。我没有测试过。

关于java - 如何将从数据库收集的数据存储在对象数组中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3538611/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com