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/
Related
How can I update my SQL Table column with the value that is stored in a local variable.
In my program I have taken value from the HTML page using the following statement:
String idd=request.getParameter("id");
String report=request.getParameter("rprt");
So now I have to update the value of report in my database table named "ptest" and I am using the following query:
Class.forName("com.mysql.jdbc.Driver");
java.sql.Connection con =
DriverManager.getConnection("jdbc:mysql://localhost:3306/tcs","root","root");
Statement st= con.createStatement();
ResultSet rs;
int i=st.executeUpdate("update ptest set result = #reprt where patient_id=
#idd");
out.println("Successfully Entered");
But the value is not being stored in the database instead NULL is being stored.
I have already seen this question and got no help.
Question
Please ignore my mistakes if any in this question as I am new to MYSQL.
You can use prepared statements in java.
setString or setInt can set different data types into your prepared statements.
The parameter 1, 2 are basically the positions of the question mark. setString(1,report) means that it would set the string report in the 1st question mark in your query.
Hope this code helps you in achieving what you want.
String query = "update ptest set result = ? where patient_id = ?";
PreparedStatement preparedStatement = con.prepareStatement(query);
preparedStatement.setString(1, report);
preparedStatement.setString(2, idd);
preparedStatement.executeUpdate();
In JDBC, you use ? as placeholders for where you want to inject values into a statement.
So you should do something like this ...
Class.forName("com.mysql.jdbc.Driver");
java.sql.Connection con =
DriverManager.getConnection("jdbc:mysql://localhost:3306/tcs","root","root");
PreparedStatement st= con.prepareCall("update ptest set result = ? where patient_id=
?");
///now set the params in order
st.setString(1, report);
st.setString(2, idd);
//then execute
st.executeUpdate();
Doing a string concat with the values is dangerous due to sql injection possibilities, so I typically make statement text static and final, and also if your value has a ' in it that could blow up your sql syntax etc. Also, notice the use of executeUpdate rather than query.
Hope this helps
here is the code there is catch close but i delete it so can anyone replay to me
String id = null;
String root="root",student="root";
String name=jTextField1.getText();
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection
con=(Connection)DriverManager.getConnection
("jdbc:mysql://localhost:3306
/dijlafinal1",root,student);
String query2="SELECT * FROM name WHERE name like ? ";
PreparedStatement pstm2=null;
pstm2=con.prepareStatement(query2);
pstm2.setString(1,"%"+name+"%");
ResultSet rs = pstm2.executeQuery(query2 );
while (rs.first()){
String name1=rs.getString("name");
id= rs.getString("id");
int epo =rs.getInt("epo");
}
jTextField2.setText(id);
}
You need to use the no-argument version of executeQuery(), i.e.
ResultSet rs = pstm2.executeQuery();
The reason is that you've already prepared the statement when you called con.prepareStatement(query2). Calling executeQuery(query2) will throw away the prepared SQL and execute the query without bind variables, leaving the ? in place -- as the error message suggests.
When working with a PreparedStatement you always call the .execute... methods without any arguments because you have already supplied the SQL command text with the .prepareStatement call. So
ResultSet rs = pstm2.executeQuery(query2 );
is incorrect. You need to simply do
ResultSet rs = pstm2.executeQuery();
I wonder if it might work if you use this?
pstm2.setString(1,"'%"+name+"%'");
Here's how I'm able to execute my stored procedure through SqlDeveloper
var p refcursor;
exec DMG.Getstudentids(12342343,:p);
print p;
Output
P
-----------
STUDENT_ID
-----------
23432425
54353455
Now I'm trying execute the stored procedure the same way but in Java. Here's my code and I'm missing something about the input/output parameters or their datatypes.
Connection connection = DriverManager.getConnection(url, user, pass);
CallableStatement cs = connection.prepareCall("{call DMG.Getstudentids(?,?)}");
cs.setFloat(1, 12342343);
cs.registerOutParameter(2, Types.OTHER);
cs.execute();
List<Integer> result = (List<Integer>) cs.getArray(2);
I get the following error
java.sql.SQLException: Invalid column type: 1111
I think I'm missing something fundamental here. Anyone see where I'm failing? Thanks.
Try following:
Connection connection = DriverManager.getConnection(url, user, pass);
CallableStatement cs = connection.prepareCall("{call DMG.Getstudentids(?,?)}");
cs.setFloat(1, 12342343);
cs.registerOutParameter(2, OracleTypes.CURSOR);
cs.executeQuery();
ResultSet resultSet=cs.getObject(1);
List<Integer> result = new ArrayList<Integer>();
while(resultSet.next()){
result.add(resultSet.getInt(STUDENT_ID));
}
Note : Since the procedure is returning refcursor, you need to register OracleTypes.CURSOR as output parameter.
Nother thing to note is you need to catch the whole dataset(refcursor) into Result Set, iterate it and put the extracted value into List.
I have done below sample JDBC program which retrieving user details.Now i am getting surprised that from same callable statement i am getting different result set for same output parameter index.Ideally it should return same ResultSet object.
when i got the resultset then i am moving cursor -1 to 0.
i am retrieving data from another resultset for the same output param using
column name then i am getting following exception
,
Exception in thread "main" java.sql.SQLException: Missing defines
System.out.println("Before loading connection");
DriverManager.registerDriver(new oracle.jdbc.OracleDriver());
Connection connection = DriverManager.getConnection(
"jdbc:oracle:thin:#170.45.3.165:1541/testdb.mycomp.com",
"admin", "admin123");
System.out.println("Connection loaded " + connection);
CallableStatement callProcedure = connection
.prepareCall("{call ADMIN_USER.Fetch_User_Details(?,?)}");
callProcedure.setString(1, "userid=testid");
callProcedure.registerOutParameter(2, oracle.jdbc.OracleTypes.CURSOR);
callProcedure.execute();
ResultSet resultUserDetails = (ResultSet) callProcedure.getObject(2);
resultUserDetails.next();
ResultSet resultUserDetails1 = (ResultSet) callProcedure.getObject(2);
String username = resultUserDetails1.getString(COL_NAME_USER_NAME);
System.out.println(resultUserDetails);
System.out.println(resultUserDetails1);
System.out.println(resultUserDetails == resultUserDetails1);
Can anyone has any idea why we are getting two different resultset for same output index from callable statement?
According to CallableSatement API the expression should be like this
{call <procedure-name>[(<arg1>,<arg2>, ...)]}
try
CallableStatement callProcedure = connection.prepareCall("{call ADMIN_USER.Fetch_User_Details(?,?)}");
Have you tried to check if only reference are different (maybe due to proxy or dirty state because you perform a next() before the second `getObject())?
try
ResultSet resultUserDetails = (ResultSet) callProcedure.getObject(2);
ResultSet resultUserDetails1 = (ResultSet) callProcedure.getObject(2);
System.out.println(resultUserDetails);
System.out.println(resultUserDetails1);
// Check ref or object equality
System.out.println(resultUserDetails == resultUserDetails1);
System.out.println(resultUserDetails.equals(resultUserDetails1));
resultUserDetails.next();
String username = resultUserDetails.getString(COL_NAME_USER_NAME);
resultUserDetails1.next();
String username1 = resultUserDetails1.getString(COL_NAME_USER_NAME);
System.out.println(username);
System.out.println(username1);
// We read the same username or we are reading first and second username?
// If the are different probably resultset is the same, just with different
// reference
System.out.println(resultUserDetails.equals(resultUserDetails1));
I am having the hardest time calling an Oracle stored procedure from a java runtime environment. The stored procedure that I am calling has 2 parameters 1 in and 1 out. Here is how I call the stored procedure... How do you get the resultSet from an Oracle ref_cursor
ds = (DataSource)initialContext.lookup("JDBC/EPCD13DB");
conn = ds.getConnection();
callableStatement = conn.prepareCall(storedProcCall);
callableStatement.setString(1, input1);
callableStatement.registerOutParameter(2, OracleTypes.CURSOR);
callableStatement.execute();//(ResultSet) callableStatement.getObject(1);
ResultSet rs = callableStatement.getResultSet();
while(rs.next()){
Provider tempProv = new Provider();
tempProv.setResourceId(rs.getLong("res_id"));
tempProv.setFirstName(rs.getString("First_Name"));
tempProv.setLastName(rs.getString("Last_Name"));
tempProv.setMiddleName(rs.getString("Middle_Name"));
ObjList.add(tempProv);
}
rs.close();
You should be able to retrieve the ResultSet with:
ResultSet rSet = (ResultSet)callableStatement.getObject(2);
Does this help you? Seems like you have to call getObject and cast it into a result set before querying on the result set.
Credit:: http://www.mkyong.com/jdbc/jdbc-callablestatement-stored-procedure-cursor-example/
I believe it returns only one output(oracle cursor)
ResultSet rs=(ResultSet) callableStatement.getObject(2);
and then iterate your cursor result set for records inside:
while(rs.next()){
Provider tempProv = new Provider();
tempProv.setResourceId(rs.getLong("res_id"));
tempProv.setFirstName(rs.getString("First_Name"));
tempProv.setLastName(rs.getString("Last_Name"));
tempProv.setMiddleName(rs.getString("Middle_Name"));
ObjList.add(tempProv);
}
In spring framework fetching database cursor results can be easily achieved. It has inbuilt classes like maprow, storedprocedure to serve the purpose. PFB the link
http://static.springsource.org/spring/docs/3.1.x/spring-framework-reference/html/jdbc.html#jdbc-simple-jdbc-call-1