gpt4 book ai didi

java - 将结果数组从类返回到其他类 java

转载 作者:行者123 更新时间:2023-12-01 13:19:12 25 4
gpt4 key购买 nike

首先我对我的英语感到抱歉,我是 Java 编程新手,我正在尝试从数据库获取结果值。 jdbc derby 上的类到另一个类这是我的代码:

package myjavaproject;

import java.sql.*;

public class Db {

private static String dbURL = "jdbc:derby://localhost:1527/hotels;create=true";
private static String tableName = "users";
// jdbc Connection
private static Connection conn = null;
private static Statement stmt = null;
public String data = null;

public static void main(String[] args) {
createConnection();
shutdown();
}

private static void createConnection() {
try {
Class.forName("org.apache.derby.jdbc.ClientDriver").newInstance();
//Get a connection
conn = DriverManager.getConnection(dbURL);
}
catch (Exception except) {
except.printStackTrace();
}
}

public static String selectUsers() {
try {
stmt = conn.createStatement();
ResultSet results = stmt.executeQuery("select * from " + tableName);
Results name = new Results();
if(results.next()){
name.setName(results.getString("name"));
String rs = results.getString("name");
//return rs;
}


results.close();
stmt.close();
}
catch (SQLException sqlExcept) {
sqlExcept.printStackTrace();
}
return null;
}

private static void shutdown() {
try {
if (stmt != null) {
stmt.close();
}
if (conn != null) {
DriverManager.getConnection(dbURL + ";shutdown=true");
conn.close();
}
}
catch (SQLException sqlExcept) {
}

}

}

最佳答案

您可能真正想要的是一个服务类,它充当 Controller 来为您配置所有内容。

类似于:

public class Service() {
private Db databaseConnection;
private List<User> users;

public Service() {
databaseConnection = new Db();
}

public List<Users> getUsers() {
users = new ArrayList<User>();
rs = databaseConnection.selectUsers(); //you'd need to change this to return the list of users, or to return the result set
if (rs != null && rs.size() > 0) {
while(rs.hasNext()) {
User aUser = new User();
aUser.setName(rs.next().get("Name")); //pseudo-code
users.add(aUser);
}
}
return users;
}
}

关于java - 将结果数组从类返回到其他类 java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22183052/

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