1

I am using JDBC and PostgreSQL as database, I was trying to create a logic in such a way that we can fetch all the data from a table, whatever table name user gives in the input it should get fetched, but the issue here is, I don't know how to do that.

Whenever we used to fetch table data from the database we are required to specify the the type of data we are getting on every index while we use ResultSet.

How to overcome from this hardcoded need of providing this metadata and make our code more general for any table with any number of columns and with any type

My code:

Statement sttm = con1.createStatement();
System.out.println("Enter table name (usertable)");
String name = sc.next();
String tableData="";

String qu = "select * from "+name;
ResultSet rs =sttm.executeQuery(qu);
while(rs.next()) {
    // here we need to define the type by writing .getInt or getString
    tableData = rs.getInt(1)+":"+rs.getString(2)+":"+rs.getInt(3);
    System.out.println(tableData);
}
System.out.println("*********---------***********-----------**********");
sttm.close();

Anyone please suggest me some way to do it.

2 Answers 2

1

You can use ResultSet.getObject(int). getObject will automatically retrieve the data in the most appropriate Java type for the SQL datatype of the column.

To retrieve the number of columns, you can use ResultSet.getMetaData(), and then use ResultSetMetaData.getColumnCount() to retrieve the number of columns.

In short, to print all columns of all rows, you can do something like:

try (ResultSet rs = stmt.executeQuery(qu)) {
    ResultSetMetaData rsmd = rs.getMetaData();
    int columnCount = rsmd.getColumnCount();
    while (rs.next()) {
        StringBuilder tableData = new StringBuilder();
        for (int colIdx = 1; colIdx <= columnCount; colIdx++) {
            tableData.append(rs.getObject(colIdx));
            if (colIdx != columnCount) {
                tableData.append(':');
            }
        }
        System.out.println(TableData);
    }
}

You can also use ResultSetMetaData to get more information on the columns of the result set, for example if you need specific handling for certain types of columns. You can use getColumnType to get the java.sql.Types value of the column, or getColumnTypeName to get the type name in the database, or getColumnClassName to get the name of the class returned by ResultSet.getObject(int/String), etc.

However, as Sorin pointed out in the comments, accepting user input and concatenating it into a query string like you're currently doing, makes you vulnerable to SQL injection. Unfortunately, it is not possible to parameterize object names, but you can mitigate this risk somewhat by 1) checking the table against the database metadata (e.g. DatabaseMetaData.getTables), and 2) using Statement.enquoteIdentifier (though this won't necessarily protect you against all forms of injection).

Sign up to request clarification or add additional context in comments.

5 Comments

Should use a PreparedStatement though to guard against SQL Injection via user supplied table name.
@Sorin right, is there any way to do it in jdbc ? is that above code will help !
@Sorin You can't parameterize object names like tables, so you cannot use a PreparedStatement to protect against SQL injection at that point. However, JDBC 4.3, does provide Statement.enquoteIdentifier to address this somewhat.
just replace qu with "show tables;"
@Rohitgupta That is a database specific solution, while the DatabaseMetaData.getTables is database agnostic. As an aside, it wouldn't actually address the question, as that asks about retrieving all data from any table, not about retrieving all the tables (not withstanding the title).
0

If you want to print data of any table from a database then check my github project over CRUD java MySQL

https://github.com/gptshubham595/jdbc_mysql_CRUD-JAVA-

These are implemented

enter image description here

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.