gpt4 book ai didi

java - 如何使用 Java 获取(检索)mysql 数据库数据到数组列表并使用索引打印

转载 作者:行者123 更新时间:2023-11-29 15:38:36 26 4
gpt4 key购买 nike

我需要获取(检索)mysql数据库数据到java数组列表并使用索引一一打印...

我已经尝试了正常的 do-while 检索,但我需要将值放入数组列表...

public class Portdetails 
{

public static void main(String[] args) {
try{
Class.forName("com.mysql.jdbc.Driver").newInstance();

try ( Connection cn = (Connection) DriverManager.getConnection("jdbc:mysql://localhost/airportinfo","root",""))
{
Statement smt=(Statement) cn.createStatement();

//query to display all records from table employee
String q="SELECT * FROM airportinfo";

//to execute query
ResultSet rs=smt.executeQuery(q);

//to print the resultset on console
if(rs.next()){
do{
System.out.println(rs.getString(1)+"--"+rs.getString(2)+"--"+rs.getString(3)+"--"+rs.getString(4));
}while(rs.next());
}
else{
System.out.println("Record Not Found...");
}
}
}
catch(Exception e)
{
System.out.println(e);
}
}

}

最佳答案

如果我理解正确,并且假设您的代码按预期工作,您只需创建一个 ArrayList 并在循环中添加项目:

public static void main(String[] args) {
List<String> itemList = new ArrayList<String>();
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();

try (Connection cn = (Connection) DriverManager.getConnection("jdbc:mysql://localhost/airportinfo", "root",
"")) {
Statement smt = (Statement) cn.createStatement();

// query to display all records from table employee
String q = "SELECT * FROM airportinfo";

// to execute query
ResultSet rs = smt.executeQuery(q);

// to print the resultset on console
if (rs.next()) {
do {
String resString = rs.getString(1) + "--" + rs.getString(2) + "--" + rs.getString(3) + "--"
+ rs.getString(4);
itemList.add(resString);
} while (rs.next());
} else {
System.out.println("Record Not Found...");
}
}
} catch (Exception e) {
System.out.println(e);
}

}
}

关于java - 如何使用 Java 获取(检索)mysql 数据库数据到数组列表并使用索引打印,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57936061/

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