#1
  1. No Profile Picture
    got Rice?
    Devshed Novice (500 - 999 posts)

    Join Date
    Nov 2004
    Posts
    518
    Rep Power
    10

    Dynamic/Variable variable names in Java.


    stupid question, I know

    In PHP, there is the ability to use dynamic variable names, i.e.

    Code:
    $a = "";
    $fromDb = "a";
    $$fromDb = "some result from DB";
    
    echo $a; // outputs:  some result from DB
    There is no java equivalent and in searching, it is either using HashMap or at worst case, using Inflection (by using the class and setter methods to set the variable).

    All I want, is to grab a field from a database, and set a variable of the same name to a value.

    Code:
    -- returns 150 rows
    SELECT fieldname, fieldvalue FROM table WHERE id=50
    Inflection would require me adding 150 setter functions, and from what I read, would be slow.

    So it seems the way to do it is via HashMap ?
    Code:
    while(rs.next() ) {
    map.add(rs.getString("fieldname"), rs.getInt("fieldvalue")); // needs to be casted to Integer obviously
    }
    
    field1 = map.get("field1"); //downcast to primitive
    ...
    field150 = map.get("field150"); //downcast to primitive
    Wondering if there is a better way to go about this?

    I thought about changing the SQL to return 1 row of 150 columns, but that turns small query into a query 60 times its size (in # of lines, along with the amount of joins it is running), and in practice, In the web application, would come back with OutOfMemory Errors (on only 168 rows results that would have been returned)

    Just wanted to post to see if there are any other ideas in going about this.
    Last edited by jaeSun; January 4th, 2013 at 05:51 PM.
  2. #2
  3. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jan 2013
    Posts
    1
    Rep Power
    0
    I am not sure what you really want to do. However I guess you just want to get access to the query result to iterate it i.e. to show it in a list on a datatable.

    Well the way it works on Java is very different than in PHP. Here you got more powerful ways to achieve this.

    I.E.

    Code:
    public List<Clients> findClientsByCountry(String country){
    	  if(country != null && country != ""){
    		  return (List<Clients>) genericDao.get(Constants.NamedQuery_FIND_CLIENTS_BY_COUNTRY, country);
    	  }
      }
      
      public void loadClientsListByCountry(){
    	  List<Clients> listClients = (List<Clients>) findClientsByCountry(country);
    	  for(Clients client: listClients){
    		  System.out.println(client.getName());
    	  }
      }
    This will iterate the list of clients for as many clients as It contains (clients objects which are mapped by the entity)

    This is using entities as example (you really should use entities and mapping with hibernate in case you do any web project)

    If you don't understand something or I did understood wrongly your question please don't hesitate on asking again. I am glad to help you as I have worked for years with PHP+J2e
  4. #3
  5. No Profile Picture
    got Rice?
    Devshed Novice (500 - 999 posts)

    Join Date
    Nov 2004
    Posts
    518
    Rep Power
    10
    I am basically writing the data to an excel file.

    the above code is per row of the excel file.

    basically:

    Code:
    // query to grab all clients
    while( rs.next() ) {
    
        clientid = rs.getInt("clientid");
    
        // query to get data for each client 
        //SELECT fieldname, fieldvalue FROM table WHERE clientid=50
    
        // results are 150 rows, fieldname1 - fieldname150 and their respective values
        while( rs.next() ) {
            map.add( fieldname, fieldvalue );
        }
    
        // do some processing based on what the values are (which vary depending on the fieldname)
        if( map.get(fieldname1) == some value ) { 
            // process
        }
        // do this for 150 fields
    
        //export to excel, clientid,fieldname1,...,fieldname150
    
    }
    fieldnames arent in order that they need to be for the excel and they need to be processed a certain way with each of the different fieldnames.

    the query to grab the fieldnames returns 150 rows. It was why initially, I tried to make it a horizontal table (return 1 row with 150 columns, and just run SELECT fieldname1, fieldname2 FROM table), so I could just grab the fieldname by rs.getString("fieldname1") and process them. I could just run one query for the whole export. But that query is big and takes a long time to run and gives an OutOfMemory error. So I think the above code is what I came up with.

    With php, I would just do something like this:

    Code:
    // obviously not php code
    // query to grab all clients
    while( rs.next() ) {
    
        clientid = rs.getInt("clientid");
    
        // query to get data for each client SELECT fieldname, fieldvalue FROM table WHERE clientid=50
    
        // results are 150 rows, fieldname1 - fieldname150 and their respective values
        while( rs.next() ) {
            $fieldname = rs.getString("fieldname");
            $$fieldname = rs.getString("fieldvalue");
        }
    
        // do some processing based on what the values are (which vary depending on the fieldname)
        if( $fieldname1 == some value ) { 
            // process
        }
        // do this for 150 fields
    
        //export to excel, clientid,fieldname1,...,fieldname150
    
    }
    Last edited by jaeSun; January 7th, 2013 at 10:46 AM.
  6. #4
  7. Contributing User
    Devshed Regular (2000 - 2499 posts)

    Join Date
    May 2004
    Location
    Superior, CO, USA
    Posts
    2,418
    Rep Power
    1713
    The code you've come up with is about what I would recommend. Depending on what processing needs to be done with each variable that you get from the DB you could also never need to know the column name:


    java Code:
    // query to grab all clients
    Map<String, String> map = new HashMap<String,String>(); // or whatever type of Map you want.
     
    // query to get data for each client 
    ResultSet rs = stmt.executeQuery("SELECT fieldname, fieldvalue FROM table WHERE clientid=50");
    ResultSetMetaData rsmd = rs.getMetaData();
     
    // results are 150 rows, fieldname1 - fieldname150 and their respective values
    while( rs.next() ) {
        clientid = rs.getInt("clientid");
     
        for( int index = 0; index < rsmd.getColumnCount(); index++ )
            map.put( rsmd.getColumnName(index), rs.getString(index) );
     
        // now all data for a single row is in the map
        for( String nextKey: map.keySet() ) {
     
        // do some processing based on what the values are (which vary depending on the fieldname)
            if( map.get(nextKey).equals( "some value" ) { 
            // process
            }
            // do this for 150 fields
     
            //export to excel, clientid,fieldname1,...,fieldname150
        }
        map.clear(); // reset the map for the next row
    }


    Note that this assumes that all column values can be converted to a String. BLOB's and any binary data do not tend to convert or convert well. If you do not want the columns to be converted to String (you may want a different date/time format for example) then you can still use the map but make it a <String,Object> and use getObject() instead of getString() from the ResultSet.

    Java is a strongly typed language. Because of that variables are pre-defined. What you want to do would work in a loosely typed language like PHP or JavaScript. That isn't a criticism of either Java or PHP - they're just different.

    And as an aside, in Java you likely do not want to do:

    java Code:
    if( map.get(fieldname1) == some value ) {


    assuming that the value in your map is defined as a String. You'll want to use the "equals" method:

    java Code:
    if( map.get(fieldname1).equals( "some value" ) {


    The == operator for Strings only would compare if they were the same String at the same address. This is very unlikely to be what you want.

IMN logo majestic logo threadwatch logo seochat tools logo