How to get column values ​​without knowing the type of column

I am creating a query dynamically based on a user who selects the fields that will be displayed as a result. The problem is that when data needs to be retrieved from the database, I usually use methods getXXX()to get the appropriate type. But in this case, I do not know what the corresponding type is, since the columns are randomly selected.

Is there a way to get the data in string format without specifying the data type XXX? I use MySQL and servlets.

+5
source share
2 answers

You can use the general getObject method :

ResultSet Java.

Java . Java Java , SQL, , JDBC. SQL NULL, Java.

+11

, getString(), Java String. , MySQL Java, getXXX(). init script:

DROP TABLE IF EXISTS thing;

CREATE TABLE thing (
  a_int int,
  a_string text,
  a_date date
);

INSERT INTO thing (a_int, a_string, a_date)
   VALUES ('1234', 'Hello world', CURRENT_DATE() );

:

public static void main(String[] args) throws Exception {
    MysqlDataSource db = new MysqlDataSource();
    db.setDatabaseName("test");
    Connection conn = db.getConnection("test", "test");

    ResultSet res = conn.prepareStatement("SELECT * FROM thing").executeQuery();
    res.next();
    System.out.println("Get a int as a string: " + res.getString("a_int"));

}

Get a int as a string: 1234. a_date Java int, 2013 . , , , . , , getInt() TEXT.

0

All Articles