I'm using JDBC to execute Oracle statement which looks like this:
"INSERT INTO MYTABLE(MYDATA) VALUES(?) RETURNING MY_CALCULATED_DATA INTO ?"
// MYTABLE's def makes MY_CALCULATED_DATA be auto-generated by DB on insert
I found several ways to call the statement above in Java, mainly:
Using OraclePreparedStatement:
ps = (OraclePreparedStatement)conn.prepareStatement(sql);
ps.setString(1, "myvalue");
ps.registerReturnParameter(2, Types.VARCHAR);
ps.execute();
rs = ps.getReturnResultSet();
rs.next();
System.out.print(rs.getString(1));
Using CallableStatement:
cs = conn.prepareCall(sql);
cs.setString(1, "myvalue");
cs.registerOutParameter(2, Types.VARCHAR);
cs.execute();
System.out.print(cs.getString(1));
Thank you, AG.
Q 5 - Which of the following is correct about PreparedStatement? A - PreparedStatement allows mapping different requests with same prepared statement but different arguments to execute the same execution plan.
JDBCJava 8MySQL. The PreparedStatement interface extends the Statement interface it represents a precompiled SQL statement which can be executed multiple times. This accepts parameterized SQL quires and you can pass 0 or more parameters to this query.
1. PreparedStatement allows you to write a dynamic and parametric query. By using PreparedStatement in Java you can write parameterized SQL queries and send different parameters by using the same SQL queries which is a lot better than creating different queries.
The PREPARE statement prepares a SQL statement and assigns it a name, stmt_name , by which to refer to the statement later. The prepared statement is executed with EXECUTE and released with DEALLOCATE PREPARE . For examples, see Section 13.5, “Prepared Statements”. Statement names are not case-sensitive.
Because parameters specified in returning clauses are handled in a different way compared to normal output parameters(getReturnResultSet vs getResultSet vs returning parameters in a callablestatement).
They need to be handled with OraclePreparedStatement. In the second case when you wrap the insert statement in begin..end the insert is handled by the database itself and al jdbc sees is an anonymous plsql block.
http://docs.oracle.com/cd/E11882_01/java.112/e16548/oraint.htm#BABJJDDA
To get auto generated key we have method getGeneratedKeys method in preparestatement which return resultset that contain key value all we need is pass key column name to preparestatement
pstm = con.prepareStatement("insert query",new String[]{primarykeycolumnname});
int i = pstm.executeUpdate();
if (i > 0)
{
ResultSet rs = pstm.getGeneratedKeys();
while(rs.next())
{
System.out.println(rs.getString(1));
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With