开发者

How to translate column names to variables in Java program?

Suppose you have thousands of rows of data coming from a table

    Index      | First_name       |    Last_name 
=====================================================
    1          |  John            |     Doe
    2          |  Jane            |     Doe

The task is to represent each individual row of this table in some bean. For example, it would be nice to have

private int index;
private String firstName
private String lastName

Unfortunately number of columns and column names is not known and beans can't be created ahead of harvesting data

I therefore can not hardcode variables name to expect a firstNa开发者_JAVA百科me. I don't know how many variables i need and the type of these variables.

Is there a way i can represent a row in a table as part of a bean where variable names are the same as column names?

The idea here is that i ultimately would have to compare 'n' of these beans and would like to intelligently report on the differences

I suppose i can have

Set<String> columnNames
List<Object> columnData

And then match by index, but is there a cleaner way?


I think a better way to represent your data would be a Map<String, Object> for each line, instead of a custom Bean class which you would have to create first ... and which you can't really use afterwards, without knowing which properties (e.g. get/set pairs) it has.

Reflection can't create classes (or interfaces), though you could use some bytecode manipulation library, or generate Java source code and pass it to the compiler. (But still, how would you use the class afterwards? Still only with reflection.)


If you are using JDBC, you could use ResultSet.getMetaData() to get additional information about the columns being returned in your resultset, their names and their types.


Well, in theory you could use a bytecode manipulation library (like BCEL: http://bcel.sourceforge.net/) to create classes on the fly, then load them into your JVM.

However, this is unlikely to be worth the effort. Perhaps you should ask yourself why the database columns have to be fields in a Java class. What are you planning to do with them?


This should get you started on reading the column names and types (assume connection is a java.sql.Connection):

    DatabaseMetaData metadata = connection.getMetaData();
    ResultSet rsColumns = metadata.getColumns(null, null, "tablename", null);
    while (rsColumns.next()) 
    {
      String columnName = rsColumns.getString("COLUMN_NAME");
      String columnType = rsColumns.getString("TYPE_NAME");

      // Do your magic

    }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜