首先我很抱歉我的英语, 我是Java编程的新手,我正在尝试从DB获取结果值。类到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) {
}
}
}
答案 0 :(得分:1)
您真正想要的是一个服务类,它充当控制器,为您配置所有内容。
类似的东西:
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;
}
}