Java - MySQL Calling Stored Procedure - java

I'm trying to call a Stored Procedure from Java. However, what I did was looking for a Function instead. What did I miss? Here's what I have tried so far;
open();
try {
statement = conn.prepareStatement(StringConstant.PROC_GET_POSITIONS);
ResultSet resultSet = statement.executeQuery();
while( resultSet.next() ){
System.out.println(resultSet.getString(0));
}
} catch ( SQLException sqlEx ) {
sqlEx.printStackTrace();
}
close();
Throwing this Exception;
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: FUNCTION test.get_positions does not exist
This is how the stored procedure is written (This is for the purpose of testing):
CREATE FUNCTION get_positions(OUT o_position VARCHAR(25))
BEGIN
SELECT pos_name
INTO o_position
FROM master_position;
END;
The reason I made the question is that SO suggested this titles:
-automate call stored procedure 1
-How to Call a Stored Procedure within a Stored Procedure in MySQL 1
-Calling a Stored Procedure in Hibernate 2
-Call a Stored Procedure From a Stored Procedure and/or using COUNT 2
-mysql stored procedure call hibernate 2
None of those answered my question.

I'm right now with this problem. I found this:
Connection conn = getMySqlConnection();
// Step-2: identify the stored procedure
String simpleProc = "{ call simpleproc(?) }";
// Step-3: prepare the callable statement
CallableStatement cs = conn.prepareCall(simpleProc);
// Step-4: register output parameters ...
cs.registerOutParameter(1, java.sql.Types.INTEGER);
// Step-5: execute the stored procedures: proc3
cs.execute();
// Step-6: extract the output parameters
int param1 = cs.getInt(1);
System.out.println("param1=" + param1);
I think this could be a great example.
Source: http://www.java2s.com/Code/Java/Database-SQL-JDBC/CallStoredProcedureInMySql.htm

You are trying to get the result from the stored procedure. Stored procedures do not return values instead Function does.

Statement stmt;
stmt = conn.createStatement();
stmt.execute(String.format("CALL swap_devices(%d,%d)", oldDeviceID, newDeviceID));

Related

Sybase and jdbc- Proc returns select statement - records not able to get

I'm executing a stored procedure from jdbc. The procedure returns the contents of a table 'out_table' which consists of 2 columns key and value, via select query.
I'm using
String query = "{? = call my_proc}";
try {
stmt = conn.prepareCall(query);
stmt.registerOutParameter(1, Types.JAVA_OBJECT);
boolean results = stmt.execute();
while (results) {
ResultSet rs = stmt.getResultSet();
if(rs.next()) {
System.out.println(rs.getString("MSG"));
System.out.println(rs.getInt("SEQ"));
}
}
I'm not able to get any results. I can see a lot of example that returns only a single field of a table from proc and not the whole table. The type 'Types.JAVA_OBJECT', I'm not sure what to use. For me, the output table fields are string and int, respectively.
What am I doing wrong?
Note : my_proc:
CREATE PROCEDURE my_proc
AS
BEGIN
CREATE TABLE #tmp_table
(
MSG VARCHAR(255),
SEQ INT
)
//Insert contents into #tmp_table
..
..
..
SELECT * FROM #tmp_table ORDER BY SEQ
END
go
Your stored procedure doesn't have an out parameter. It produces a ResultSet instead. So you should remove the out parameter definition in your call:
String query = "{call my_proc}";
try (CallableStatement stmt = conn.prepareCall(query)) {
boolean results = stmt.execute();
while (true) {
if (results) {
// results true means: result is ResultSet
try (ResultSet rs = stmt.getResultSet()) {
if(rs.next()) {
System.out.println(rs.getString("MSG"));
System.out.println(rs.getInt("SEQ"));
}
}
} else {
// results false means: result is update count
// or no more results if updateCount is -1
int updateCount = stmt.getUpdateCount();
if (updateCount == -1) break;
// Do something with update count
}
// Move to next result
results = stmt.getMoreResults()
}
}
I added try-with-resource to correctly close resource as soon as you are done with them, I have also added code to correctly handle multiple results including update counts, which especially in Sybase (and SQL Server) might be a complication if your stored procedure doesn't use SET NOCOUNT ON. Your original code also had an infinite loop.
Note that if(rs.next()) might need to be while (rs.next) if there can be more than one result in the table.

Calling PL/SQL package code in a Java Program

I am trying to call a procedure defined with a PL/SQL package in a Java program.
I am aware one can call stored procedures using connection.prepareCall in Jdbc. But there is very little information out there on how to call a procedure within a package.
I am at a stage in development where i am still considering what db framework to use. Just wondering what are the pros and cons of using JDBC for PLSQL ? For this usecase are there better alternatives to JDBC ?
Follow the simple steps below:
public static final String SOME_NAME = "{call schema_name.org_name_pkg.return_something(?,?)}"; // Change the schema name,packagename,and procedure name.
// Simple JDBC Connection Pooling
// Here I am passing param companyId which is IN param to stored procedure which will return me some value.
Connection conn = null;
CallableStatement stmt = null;
ResultSet rset = null;
try {
conn = DriverManager.getConnection("jdbc:mysql://hostname:port/dbname","username", "password");
stmt = conn.prepareCall(SOME_NAME);//We have declared this at the very top
stmt.setString(1, companyid);//Passing CompanyID here
stmt.registerOutParameter(2, OracleTypes.CURSOR);//Refcursor selects the row based upon query results provided in Package.
stmt.execute();
rset = (ResultSet) stmt.getObject(2);
while (rset.next()) {
String orgId=rset.getString("RPT_ORG_ID");
// When using refcursor easy to get the value just by using Column name
String orgName=rset.getString("RPT_ORG_NAME");
// Some Logic based what do you want to do with the data returned back from query
} catch (Exception e) {
LOGGER.error("Error extracting ", e);
} finally {
DBUtils.cleanUp(conn, stmt, rset);
}
// Clean and close you connection

Java calling a stored proc with ref cursor return type

I've been encountering an issue where I constantly get a java.sql.SQLException: Bigger type length than Maximum error when trying to return a ref cursor from my stored procedure.
I have a very simple stored procedure which has just one output variable as a ref cursor, the ref_cursor is defined to be type ref cursor in the Oracle package named WS_SEARCHTEST.
CREATE OR REPLACE PACKAGE DB.WS_SEARCHTEST
IS
TYPE ref_cursor IS REF CURSOR;
My procedure:
PROCEDURE searchTest(query_result OUT ref_cursor)
Is
Begin
open query_result for select pay_id, member_id, group_no from member_table
where carrier_no = '7' AND group_no = '200607';
End;
I know my connection works because I've used it to run simple queries and have checked with the db. In my java code I do the following:
callStmt = connection.prepareCall("{call WS_SEARCHTEST.searchTest(?)}");
callStmt.registerOutParameter(1, OracleTypes.CURSOR);
callStmt.execute();
resultSet = (ResultSet) callStmt.getObject(1);
I have also tried:
resultSet = callStmt.executeUpdate();
AND
resultSet = callStmt.executeQuery();
However I will always get java.sql.SQLException: Bigger type length than Maximum when I try to access the resultSet.
Thanks
if you want to write a java code which will call PostgreSQL Stored procedure where
there is an INOUT refcursor.
PostgreSQL SP:
CREATE OR REPLACE PROCEDURE Read_DataDetails(INOUT my_cursor REFCURSOR = 'rs_resultone')
LANGUAGE plpgsql
AS $$
BEGIN
OPEN my_cursor FOR Select * from MyData;
END;
$$;
corresponding java code will be:
connection = getConnection(your connection parameter);
if (connection != null) {
connection.setAutoCommit(false); // This line must be written just after the
//connection open otherwise it will not work since cursor will be closed immediately.
String readMetaData = "CALL Read_DataDetails(?)";
callableStatement = connection.prepareCall(readMetaData);
callableStatement.registerOutParameter(1, Types.REF_CURSOR);
callableStatement.execute();
rs = (ResultSet) callableStatement.getObject(1);
if (rs != null) {
while (rs.next()) {
<Your Logic>
}//end while
}//end if
}//end if

Call procedure included in oracle package

I have created a package in my Oracle database which includes several procedures, now I want to call procedure from java program procedure requires two input parameter and returns nothing.
Please help me to do so, I have been using below connection to connect to database:
String i =username.getText();
String j =psswd.getText();
String k = sid.getText();
Class.forName("oracle.jdbc.driver.OracleDriver");
con=DriverManager.getConnection("jdbc:oracle:thin:#ora211g.home.com:1654:ora11g",username,password);
st = con.createStatement();
rs =st.executeQuery("SELECT DISTINCT SUBJECT_AREA FROM REP_SUBJECT");
This thing is working fine, now how can I call procedure by passing some parameter (say two string values)
This useful blog posting will help you
http://jameajudo.blogspot.com.br/2009/03/call-procedure-oracle-with-java-and.html
The example he uses is:
String command = "{call SALDOS(?,?)}";
CallableStatement cstmt = con.prepareCall (command);
cstmt.registerOutParameter(2, Types.DECIMAL);
cstmt.execute();
2This is what you want
st = con.prepareStatement("SELECT DISTINCT SUBJECT_AREA FROM REP_SUBJECT WHERE A = ? AND B = ?");
st.setString(1, "val1");
st.setString(2, "val2");
rs =st.executeQuery();
Using con.prepareCall().
And then using the CallableStatement object that is returned for setting params and execution.
Here I got the solution of my question so thought of posting it here so that everybody can understand in detail:
Connection con = null;
ResultSet rs = null;
Statement st = null;
Class.forName = Class.forName("oracle.jdbc.driver.OracleDriver");
con=DriverManager.getConnection( "jdbc:oracle:thin:#host:port:SID);
CallableStatement csmt = con.prepareCall("{call PACKAGE_NAME.PROCEDURE_NAME(?,?,?,?)}");
csmt.setString(1,"abc");
csmt.setString(2,"def");
csmt.setString(3,"ghi");
csmt.registerOutParameter(4,java.sql.Types.VARCHAR);
csmt.execute();
String message =csmt.getString(4);
here '?' indicates the number of input and output parameters in your procedure. I had 3 input and 1 output parameter so number of '?' in procedure are 4.
there indexing start with 1,2,3....
my first three input parameter are a string, so i am passing them to procedure using :
csmt.setString(1,"abc");
csmt.setString(2,"def");
csmt.setString(3,"ghi");
my Procedure returns string, so in order to get receive that in java first I have to register the out parameter so I have done the same using :
csmt.registerOutParameter(4,java.sql.Types.VARCHAR); /*4 becuase out parameter is 4th*/
Then I have executed callable statement and after that I am receiving the return from procedure into
String message =csmt.getString(4);
Enjoy..... \M/

Error on calling a stored procedure from java - Invalid JDBC data type -10

I have a java class from which i am connecting to the SQL Server 2008 which is on a remote machine.I Can retrieve data using a class which means the connection is working fine.
But when i try to run a stored procedure it gives me
Exception as com.microsoft.sqlserver.jdbc.SQLServerException - Invalid JDBC data type -10.
Find the code below. Can anyone help me with this? I have added the sqljdbc, sqljdbc4 jars to my class buildpath.
CallableStatement cs=null;
con = SqlConnectionManager.getConnection();
cs = con.prepareCall("{call dbo.PKG_ER_SEL.sp_ERGetJobCode(?,?,?)}");
cs.setInt(1, orgId);//v_org
cs.setString(2, compCode);//v_type
cs.registerOutParameter(3, OracleTypes.CURSOR); //getting exception here
cs.executeUpdate();
ResultSet resultSet = (ResultSet) cs.getObject(3);
if (resultSet != null) {
while ( resultSet.next() ) {
JobVO obj = new JobVO();
obj.setCode(resultSet.getString("CODE"));
obj.setName(resultSet.getString("NAME"));
seqAttList.add(obj);
}
resultSet.close();
}
}catch(Exception e){
e.printStackTrace();
}finally{
SqlConnectionManager.releaseConnection(con);
}
Thanks
In JAVA get the ResultSet from the call to executeQuery on the Statement object. The ResultSet instance is the equivalent of a CURSOR in T-SQL. Read some more about using ResultSet here.
For SQL Server you call/execute a stored procedure as detailed here. A simple example would be EXECUTE my_stored_procedure if your stored procedure is called my_stored_procedure.

Categories