Home > database >  Not able to pass the result from a SQL Query to a method in JAVA
Not able to pass the result from a SQL Query to a method in JAVA

Time:11-11

This is my first time using Java and i got confused.

I created this method:

List<Map<String, Object>>resultSet= getResultInMapList(urlString, driverr, usernameString, password, sqlQuery, "323");

which pass in a harcoded value, in this case it is 323, right?

My getResultInMapList looks like this:

public static List<Map<String, Object>> getResultInMapList(String urlString, String driverr, String usernameString, String password,String sqlQuery, Object... params) throws
    SQLException, IOException {

        try {
            createConn(urlString,driverr,usernameString,password);
            if (params == null) {
            return run.query(conn, sqlQuery, new MapListHandler());
      } else {
          return run.query(conn, sqlQuery, new MapListHandler(), params);
    }
     } catch (SQLException se) {
    se.printStackTrace();
         return null;
     } finally {
    closeConn();
     }
   }

The problem is that i don't want to pass a harcoded value anymore, instead of that i want to pass the result of a SQL Query.

SQL Query:

sqlQuery2: "select name from fake_table" (it is just an example)

Expected result:

List<Map<String, Object>>resultSet= getResultInMapList(urlString, driverr, usernameString, password, sqlQuery, sqlQuery2);

The problem is that i don't know how to modify my getResultInMapList in order to make it work.

I tried doing something like this:

public static List<Map<String, Object>> getResultInMapList(String urlString, String driverr, String usernameString, String password,String sqlQuery, sqlQuery2) 

but then the "params" does not exist anymore

What should i do in order to make it work?

CodePudding user response:

Run sqlQuery2 first, store the results in a different List, then convert the List to an array:

List<Object> paramList = new ArrayList<>();

try (Statement statement = conn.createStatement()) {
    ResultSet results = statement.executeQuery(sqlQuery2);
    while (results.next()) {
        paramList.add(results.getString(1));
    }
}

Object[] params = paramList.toArray();

Whether results.getString(1) is actually the right column to retrieve will depend on your database and your query. I assume sqlQuery2 only retrieves the data it needs to retrieve.

  • Related