manout
manout

Reputation: 41

return results array from class to other class java

First I'm sorry about my English, I'm new on Java programing and I'm trying to get result values from DB. class to another class on jdbc derby this is my code:

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) {
    }

}

}

Upvotes: 0

Views: 502

Answers (1)

Uncle Iroh
Uncle Iroh

Reputation: 6045

Really what you probably want is a service class that acts as a controller to get everything configured for you.

something like:

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;
   }
}

Upvotes: 1

Related Questions