-1

How i can use a variable for the name of table in this type of request sql ?

Code :

String table="QUESTIONS_GEST";
PreparedStatement pst=conn.prepareStatement("SELECT COUNT(*) FROM TABLE(?)");
pst.setString(1,table);
ResultSet r=pst.executeQuery();
r.next();
System.out.println(r.getInt(1));

Output :

org.postgresql.util.PSQLException: ERROR: syntax error at or near "TABLE"
Position : 22

Thanks a lot for your help ! ;)

Raza Char
  • 53
  • 3
  • I don't think you can use the parameter wildcard `?` for a table name (and I don't know if Postgers has something like a *table constructor by name* (`TABLE(table_name)`). – deHaar Jul 16 '20 at 12:07
  • 1
    Does this answer your question? [Using Prepared Statements to set Table Name](https://stackoverflow.com/questions/1208442/using-prepared-statements-to-set-table-name) – jnorman Jul 16 '20 at 12:11

1 Answers1

0

You can also use replace function in java and make a query. This is also way.

String table="QUESTIONS_GEST";
String yourQuery = "SELECT COUNT(*) FROM ?"
yourQuery = yourQuery.replace("?", table);
PreparedStatement pst=conn.prepareStatement(yourQuery);
Abdusoli
  • 661
  • 1
  • 8
  • 24