0

I'm using Apache Derby. I want to extract the query from the JDBC program. I know that the questions in these lines have been asked (How can I get the SQL of a PreparedStatement?). But this question is specific to Apache Derby.

PreparedStatement stmt = conn.prepareStatement(
          "SELECT * FROM EMPLOYEE 
           WHERE SALARY BETWEEN ? AND ?");
stmt.setInt(1, 1000);
stmt.setInt(2, 100000);

Edit

After this point in the above code snippet is there way to get the actual query without executing in the DB?

I do not want to execute PreparedStatement in the DB. i.e without using stmt.execute() or stmt.executeQuery()

Curious
  • 35
  • 1
  • 8
  • 1
    @GordThompson you should have read the question fully before marking it as duplicate. I had asked for getting the query sql from `Derby`. But **without executing the query to the database**. I do not find the answer which I am expecting in the question which you have given. – Curious Oct 06 '18 at 15:00
  • What does "get the actual query without executing in the DB" mean? The actual query is right there in your code: `SELECT * FROM EMPLOYEE WHERE SALARY BETWEEN ? and ?` – Bryan Pendleton Oct 06 '18 at 16:46
  • @BryanPendleton I know that query already present in the code. What I meant is without calling `stmt.execute() or stmt.executeQuery()` in the code can I get the query? – Curious Oct 07 '18 at 03:53

1 Answers1

1

I guess, the answer is the link you mentioned.

Using prepared statements, there is no "SQL query" :

You have a statement, containing placeholders it is sent to the DB server and prepared there which means the SQL statement is "analysed", parsed, some data-structure representing it is prepared in memory And, then, you have bound variables which are sent to the server and the prepared statement is executed -- working on those data But there is no re-construction of an actual real SQL query -- neither on the Java side, nor on the database side.

So, there is no way to get the prepared statement's SQL -- as there is no such SQL.

For debugging purpose, the solutions are either to :

Ouput the code of the statement, with the placeholders and the list of data Or to "build" some SQL query "by hand".

Danny
  • 822
  • 1
  • 9
  • 30
  • There are other solutions like this one [too](https://stackoverflow.com/a/26228133/10362432) in the same question. But I want the solution for Derby – Curious Oct 06 '18 at 10:29
  • I haven't tried it yet but whats about statement.getGeneratedKeys() ? – Danny Oct 06 '18 at 10:41
  • 1
    @Curious That is specific to the MySQL driver. In most databases (and drivers), the parameters are **never** combined with the prepared statement. The statement is prepared with parameter placeholders, and a collection of parameter values is sent at execute. At best they may simulate it for debug output (and that may be tricky, because that may not necessarily be syntactically correct). – Mark Rotteveel Oct 06 '18 at 11:22