According to google and some other sources (e.g., http://www.enterprisedt.com/publications/oracle/result_set.html), if I want to call a stored-function that returns a ref cursor, I need to write something like this in order to access the ResultSet:
String query = "begin ? := sp_get_stocks(?); end;";
CallableStatement stmt = conn.prepareCall(query);
// register the type of the out param - an Oracle specific type
stmt.registerOutParameter(1, OracleTypes.CURSOR);
// set the in param
stmt.setFloat(2, price);
// execute and retrieve the result set
stmt.execute();
ResultSet rs = (ResultSet)stmt.getObject(1);
Is there anyway to do it without introducing the compile-time dependency on Oracle. Is there a generic alternative to OracleTypes.CURSOR?
Constant OracleTypes.CURSOR is -10. Quite ugly solution but you can just write -10 there or create your own constant which value is -10.
Have you tried java.sql.Types.OTHER? It might work. API says, it's for database specific types.
Related
I'm using Postgres 12 and have written this procedure:
CREATE OR REPLACE PROCEDURE reduceStock(id INTEGER, soldQuantity INTEGER)
LANGUAGE plpgsql AS
$$
BEGIN
UPDATE inventory SET ProductStockAmount = ProductStockAmount - soldQuantity WHERE ProductID = id;
END;
$$;
It works perfectly if I open up psql on the command line and run call reduceStock(1,1);
However, calling it from my Java program as follows:
CallableStatement stmt = conn.prepareCall("{call reduceStock(?, ?)}");
stmt.setInt(1, productID);
stmt.setInt(2, quantity);
stmt.execute();
Gives me the following error:
What I've Tried
running call reduceStock(1,1); from the psql client - works perfectly
dropping the database and starting over to see if some old definition was cached - didn't work
different capitalisations, spacings of call
Any ideas would be appreciated
You need to remove the curly braces, which are the JDBC escape for calling a procedure. But because Postgres has it's own call command, they are not needed (and collides with the JDBC escape).
CallableStatement stmt = conn.prepareCall("call reducestock(?, ?)");
The curly braces around the procedure inocation ({call reduceStock(?, ?)}) mean that this is not native SQL, but rather JDBC syntax. You can read more about it here: Why do JDBC calls to stored procedures wrap the call in curly brackets?.
So calls like this still have to get translated to the native SQL by the JDBC driver. It happens that the Postgres driver, by default, treats such statements as function calls and translates them to SELECT reduceStock(?, ?) SQL query. This is not how stored procedures shall be called in Postgres. In Postgres a stored procedure call SQL is call reduceStock(?, ?).
One way to make it work would be, like #a_horse_with_no_name wrote in his answer, to remove the curly braces. This makes the statement a native call and because it's a valid Postgres SQL this is going to work. The downside is that it makes it less cross-platform as it will not work for DBs that don't support the call procname() syntax. For example this won't work for Oracle, so if you have to support multiple JDBC drivers, this is the less-preferable way to go.
A better fix would be to hint Postgres JDBC driver to treat this syntax like a stored procedure call rather than a function call and translate it to SQL accordingly. For this purpose the Postgres driver exposes a escapeSyntaxCallMode configuration property (check out the EscapeSyntaxCallMode enum as well):
Specifies how the driver transforms JDBC escape call syntax into underlying SQL, for invoking procedures or functions. (backend >= 11) In escapeSyntaxCallMode=select mode (the default), the driver always uses a SELECT statement (allowing function invocation only). In escapeSyntaxCallMode=callIfNoReturn mode, the driver uses a CALL statement (allowing procedure invocation) if there is no return parameter specified, otherwise the driver uses a SELECT statement. In escapeSyntaxCallMode=call mode, the driver always uses a CALL statement (allowing procedure invocation only).
As you can see all {call something()} statements are treated like function calls by default and always translated to SELECTs. Setting escapeSyntaxCallMode to call will make the driver translate them to call SQL statements instead. The callIfNoReturn option seems most reasonable for most use-cases as it will transform JDBC calls to stored procedure calls if no return parameter has been specified and as function calls otherwise.
You can find an example of using this setting in Postgres docs (Chapter 6. Calling Stored Functions and Procedures):
// set up a connection
String url = "jdbc:postgresql://localhost/test";
Properties props = new Properties();
// ... other properties ...
// Ensure EscapeSyntaxCallmode property set to support procedures if no return value
props.setProperty("escapeSyntaxCallMode", "callIfNoReturn");
Connection con = DriverManager.getConnection(url, props);
// Setup procedure to call.
Statement stmt = con.createStatement();
stmt.execute("CREATE TEMP TABLE temp_val ( some_val bigint )");
stmt.execute("CREATE OR REPLACE PROCEDURE commitproc(a INOUT bigint) AS '"
+ " BEGIN "
+ " INSERT INTO temp_val values(a); "
+ " COMMIT; "
+ " END;' LANGUAGE plpgsql");
stmt.close();
// As of v11, we must be outside a transaction for procedures with transactions to work.
con.setAutoCommit(true);
// Procedure call with transaction
CallableStatement proc = con.prepareCall("{call commitproc( ? )}");
proc.setInt(1, 100);
proc.execute(); proc.close();>
-- https://jdbc.postgresql.org/documentation/head/callproc.html#call-procedure-example
This is the code im using in java to query the database
connect = DriverManager.getConnection (url, "user", "pass");
state = connect.createStatement();
String meetID = "SELECT GamerTag FROM backup";
ResultSet rs = state.executeQuery(meetID);
while(rs.next()){
System.out.println(rs.toString());
}
Im not getting the values of the row in the database im getting this instead
com.mysql.jdbc.JDBC4ResultSet#108137c9
You're printing the result of the toString method of the Recordset object, which appears to print out the object's name and hashcode.
Instead, try to print the value of a column. Perhaps using getString:
System.out.println(rs.getString("GamerTag"));
The documentation for Java's recordset looks confusing, you might be better off searching for examples.
What do you expect rs.toString() should do it will just print the hash of the resultsetObject if you want to get the column values you should do this way
while(rs.next()){
System.out.println(rs.getString("yourFirstColumnName")+" "+
rs.getString("yourSecondColumnName")+" "+
rs.getString("yourThirdColumnName"));
}
Really you should use PreparedStatement. In your case though you are not using any parameterizedQuery but One of the major benefits of using PreparedStatement is better performance. PreparedStatement gets pre compiled.
In database and there access plan is also cached in database, which allows database to execute parametric query written using prepared statement much faster than normal query because it has less work to do. You should always try to use PreparedStatement.
So you can do something like this
String query = "SELECT GamerTag FROM backup"
PreparedStatement st =connect.prepareStatement("query");
ResultSet rs = st.executeQuery();
I have been given an oracle procedure with the in out parameter %rowtype,like:
CREATE OR REPLACE PROCEDURE cleansing(
io_user IN OUT USER%rowtype
)
IS
BEGIN
--some pl/sql code
END cleansing;
USER is a table with more than 100 columns, I want to call the procedure by Java.
I can't change the procedure, because they are already used by other project.
I can't add procedure to database, because I don't have the permission to do it.
I google it, but can't find a good way to handle this.
what I want to do is:
1. pass the parameter.
2. get the parameter. some java demo code:
String sql = "{call cleansing(?)}";
try {
dbConnection = getDBConnection();
callableStatement = dbConnection.prepareCall(sql);
callableStatement.setXXX()//I don't know
callableStatement.registerOUTParameter(1, //I don't know the type.);
can anyone help me and give some demo code? no change to database and in out parameter mapping with java
This is possible but it's not really straightforward. You have to create something of type USER%ROWTYPE at runtime and use that to call your stored procedure. Take a look here for details.
To get output values as well, you have to do something extra, along the line of Sumit's comment. Basically, after your procedure call, you open a cursor that selects the relevant data from the USER parameter.
So you get a database statement as follows (pseudocode):
string sql =
"declare
user_param user%rowtype;
begin
-- Set necessary parameters
user_param.col0 := :p0In;
user_param.col1 := :p1In;
...
-- Call procedure.
cleansing(io_user => user_param);
-- Read necessary output values into cursor.
open :pOut for select user_param.col99 as col99
user_param.col98 as col98
...
from dual;
end;"
You call this entire statement the usual way, but you register a cursor out parameter (unfortunately, Java is a very long time ago for me so I'm not sure on the exact syntax).
callableStatement.registerOutParameter("pOut", OracleTypes.CURSOR);
...
callableStatement.execute();
...
ResultSet rs = (ResultSet) callableStatement.getObject("pOut");
// Read from result set.
EDIT: I turned this into a blogpost. Code examples are in C# but the idea is the same.
I've tried to call a stored procedure with parameter names specified, but the JDBC failed to accept the parameters. It says:
Method org.postgresql.jdbc4.Jdbc4CallableStatement.setObject(String,Object) is not yet implemented.
I use postgresql-9.2-1003.jdbc4
I there any other way to do this?
I know that I can just specify the sequence number. But I want to specify the parameter names as it is more convenient for me to do so.
My code:
String call_statement = "{ ? = call procedure_name(?, ?, ?) }";
CallableStatement proc = connection.prepareCall(call_statement);
proc.registerOutParameter(1, Types.OTHER);
proc.setObject("param1", 1);
proc.setObject("param2", "hello");
proc.setObject("param3", true);
proc.execute();
ResultSet result = (ResultSet)proc.getObject(1);
Unfortunately, using the parameter names is not a feature supported by the implementation of the JDBC 4 driver for the PostgreSQL database. See the code of this JDBC 4 implementation in GrepCode.
However, you can still continue to use an integer (variable or literal) to indicate the position of the parameter.
It's 2020 here and the standard open source JDBC driver for Postgres still doesn't support named parameter notation for CallableStatement.
Interestingly, EnterpriseDB driver does support it (with that said - I tried to use EDB JDBC driver - it indeed supports named parameters but it does so many things differently, if at all, that we ruled out this option entirly, for those other reasons)
A solution which worked for us - is to use this "hack" (pseudo-code, YMMV):
String sql = "SELECT * FROM PROC(IN_PARAM1 => ?, IN_PARAM2 => ?, IN_PARAM => ?)";
PreparedStatement ps = connection.prepareStatement(sql);
ps.setObject("IN_PARAM1", 1);
ps.setObject("IN_PARAM2", "hello");
ps.setObject("IN_PARAM3", true);
ps.execute();
ResultSet result = (ResultSet)ps.getObject(1);
The killer feature of this notation - is the ability to call SPs with optional params (it could be achieved by having optional ordinal params, but if you have more than a few of them - it becomes a nightmare, as one needs to pass so many nulls, that it's too easy to miscount, and those are very hard to spot)
There are also additional benefits, like ability to return multiple ResultSets (refcursors), ability to use maps as params, etc.
P.S.: we also use the same trick for Node.js with node-postgres - works well for years.
StringBuffer sql = new StringBuffer("{ call ? := mailmerge_package.getLetters(?, ?, ?)}");
I know it's like an sql statement but theres no such thing as 'call' in SQL.
Can someone explain to me what it means and how does it come to be understood by Java
EDIT:
import oracle.jdbc.driver.OracleTypes;
//omitted code
CallableStatement cs = null;
ResultSet rs = null;
StringBuffer sql = new StringBuffer("{ call ? := mailmerge_package.getLetters(?, ?, ?)}");
try {
cs = conn.prepareCall(sql.toString());
cs.registerOutParameter(1, OracleTypes.CURSOR);
DAOUtils.setLong(cs, 3, checklistAnsMastId);
DAOUtils.setLong(cs, 2, workEntityId);
cs.setLong(4, patientId);
DAOUtils.setLong(cs, 5, encounterId);
cs.setString(6, encounterType);
cs.execute();
rs = (ResultSet)cs.getObject(1);
This looks like SQL you can pass to Oracle.
If so then this could be used to call an Oracle function mailmerge_package.getLetters which returns a value. That value is parsed by JDBC and the Db layer to replace the first ?, this can be read into a Java variable. the Oracle function takes 3 parameters (the 3 ? in parentheses)
{call <<procedure name>>}
is a SQL escape sequence. Basically, since different databases have different syntax for how to call a user-defined procedure and different databases have different built-in functions for various things like common date/ time functions, JDBC drivers implement a number of escape sequences where the driver translates a generic specification (i.e. {call <<procedure name>>}) and expands that to be the database-specific syntax. There are various other escape sequences for things like outer joins, date literals, and string functions that can be useful if you're trying to write database agnostic code.
FYI, these escape sequences were originally defined in the ODBC API and then adopted by JDBC so you may find more documentation related to ODBC than JDBC.
It is call to an stored procedure of a database. But which database, I can't tell from this code.