0

I want to make a SELECT method that can work regardless of table structures (different number of columns, data type and etc. I'm not asking for source code. I just need some advice, ideas, or directions as to how I can get there.

Here are my code : (which only works when I know the data type and number of columns in that table)

public static void select(Connection con, String USRIDX ) throws ClassNotFoundException { 

String sql = "SELECT * from test where USRIDX =" + USRIDX;

    try(PreparedStatement pstmt = con.prepareStatement(sql)) {
        ResultSet rs = pstmt.executeQuery(sql);
        while(rs.next()) {
            String a = rs.getString(1);
            String b = rs.getString(2); 
            String c = rs.getString(3); 
            LOG.info(a +" " + b + " "+c );

        } 
    } catch(SQLException e) {
        LOG.info(e.getMessage());
    }
}      
Jin Lee
  • 3,194
  • 12
  • 46
  • 86
  • 1
    Re `String sql = "SELECT * from test where USRIDX =" + USRIDX;`: [Let me introduce you to my friend Bobby](http://bobby-tables.com)... – T.J. Crowder Dec 05 '18 at 08:13
  • 1
    *"I want to make a SELECT method that can work regardless of table structures (different number of columns, data type and etc."* Why? That would basically be recreating a subset of JDBC. Just use JDBC (`PreparedStatement` in particular, see above). – T.J. Crowder Dec 05 '18 at 08:14
  • 1
    @T.J.Crowder thank you for your insight. I'm kind of new, so just learning a whole bunch of stuff. sometimes hard to process, so weird questions come out. :) – Jin Lee Dec 05 '18 at 08:48
  • 1
    :-) Fair enough! – T.J. Crowder Dec 05 '18 at 08:52
  • Possible duplicate of [How to get row count using ResultSet in Java?](https://stackoverflow.com/questions/7886462/how-to-get-row-count-using-resultset-in-java) – SHR Dec 05 '18 at 10:40

1 Answers1

1

You can use Statement.execute(String sql). Here sql can be anything including delete or insert. If it returns true it means it was select and you call getResultSet() on the statement, otherwise you call Statement.getUpdateCount(). To know about result set columns call ResultSet.getMetaData().

Evgeniy Dorofeev
  • 133,369
  • 30
  • 199
  • 275