How do I call a stored procedure from Jasper Report?
The JasperReports Ultimate Guide contains this information about using store procedure:
Certain conditions must be met to put stored procedure calls in the SQL query string of a report template:
The stored procedure must return a java.sql.ResultSet when called through JDBC.
The stored procedure cannot have OUT parameters.
Below are the steps to call a stored procedure to build a report using iReport 4.5/4.5.1 JasperReport and using Oracle Express database.... hope this helps....
1.In your iReport designer go to Tools --> Options --> and in the Classpath Tab click Add JAR and add the OJDBC14.jar to the classpath.
2.Go to Query Executer tab and set the following Language: plsql Query Executer Factory: com.jaspersoft.jrx.query.PlSqlQueryExecuterFactory Fields Provider Class: com.jaspersoft.ireport.designer.data.fieldsproviders.SQLFieldsProvider
3.Select Database JDBC Connection
4.Select Oracle as the JDBC Driver as shown in the image below and verify the connection by clicking the Test button (Make sure you check the Save Password check box)
5.Create a blank report by giving a report name and save it.
6.Open the report in the designer and right click on the report name and click on Edit Query
7.Set the query language to plsql
8.Call your procedure with in { }
{call PUBLISHER_AND_BOOKS(&P(P_PUBLISHER_ID), &P(ORACLE_REF_CURSOR))}
Note: P_PUBLISHER_ID is of type string and ORACLE_REF_CURSOR is of type java.sql.ResultSet data type custom parameter. You can create this by clicking the New Parameter button. If you have more input parameters use ‘,’ as your delimiter as shown in the above example.
9.Click Ok and proceed with the report design.
10.In the designer window right click on Fields and add click Add Fields and make sure all the field name matches the column name in your stored procedure
11.Now right click on the parameters and add the parameters matching the stored procedure NOTE: make sure you uncheck the "Use for Prompt" in the property for your out parameter in our example its ORACLE_REF_CURSOR is the out parameter.
12.Drag and drop the fields in the report detail band as shown below
13.Click preview to run the report you will be prompted with the input parameter
All the steps are captured in detail with images and available in the below link hope this helps...
http://meezageekyside.blogspot.com/#!/2012/04/jasper-reports-ireport-45-using-oracle.html
<queryString>
<![CDATA[Call procedure_name ($P{parm1},$P{parm2},"$P!{parm3}","$P!{parm4}","$P!{parm5}",$P{parm6},$P{parm7});]]>
</queryString>
With MySQL You can call the stored procedure just like you call any other query, using the queryString.
Here is how i tackled the issue, you can easily do this by using a JR scriptlet (java bean).
Below is the sample java code and once you have the jar file add it to the jasper report
classpath and reference the same on your report properties.
-- Please make sure you use identicle names as given in your report when accessing variable/parameter
values and in setting Variable values (you can't set parameter values, just the vaiables)
package com.scriptlets;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Date;
import net.sf.jasperreports.engine.JRDefaultScriptlet;
import net.sf.jasperreports.engine.JRScriptletException;
public class Icdf extends JRDefaultScriptlet {
public void afterReportInit() throws JRScriptletException {
// get the current connection from report via parameters
Connection conn = (Connection) this
.getParameterValue("REPORT_CONNECTION");
int userId = 100; //use this.get__ to access from report
try {
if (conn != null)
callOracleStoredProcOUTParameter(conn, userId); // SP call
} catch (SQLException e) {
e.printStackTrace();
}
}
private void callOracleStoredProcOUTParameter(Connection conn, int userId)
throws SQLException {
CallableStatement callableStatement = null;
String getDBUSERByUserIdSql = "{call someStoredProcedureName(?,?,?)}";
try {
callableStatement = conn.prepareCall(getDBUSERByUserIdSql);
// setting parameters of the callablestatement
callableStatement.setInt(1, userId);
callableStatement.registerOutParameter(2, java.sql.Types.VARCHAR);
callableStatement.registerOutParameter(3, java.sql.Types.DATE);
// execute getDBUSERByUserId store procedure
callableStatement.executeUpdate();
// get the required OUT parameters from the callablestatement
String userName = callableStatement.getString(2);
Date createdDate = callableStatement.getDate(3);
// --just to check, you can view this on iReport console
System.out.println("UserName : " + userName + "CreatedDate : " + createdDate);
// set the values to report variables so that you can use them in
// the report
this.setVariableValue("variable_name1", userName);
this.setVariableValue("variable_name2", createdDate);
} catch (SQLException e) {
e.printStackTrace();
} catch (JRScriptletException e) {
e.printStackTrace();
}
}
}
very easy:
1. At tab outline. Right click to file jasper --> select Dataset & Query ...
2. Select DB, language plsql, & call with query follow
Exp:
{call packageName.procedureName( $P{a}, $P{b}, $P{c}, $P{d}) }
Good luck!
JasperReport doesn't support calling stored procedure/function directly from his SQL datasource. The best way I found to overcome that limitation is to create a Java bean that calls the stored procedure (via JDBC or Hibernate) and returns a collection of objects which represent the result set. If you're using iReport, just change the Data Source Expression to use that Java bean. There's good section on data sources in the (not free) iReport manuals.
Two possibilities for calling a procedure from Jasper reports,
If your procedure returns some result set and if you would like to
use in the report, then you have to create a function, type and type
table (for holding the result set) for calling the procedure.
If the procedure does some DML operation, then you can call directly
(without a function)
In jasper studio(I'm using v5.5.1) you can call sp like this:
Select SQL as language
just Exec your sp and pass parameters to it
here is my sp that take to DateTime parameters and returns a set of result
EXEC dbo.SP_Report #p1=$P{date_from}, #p2=$P{date_to}
In jasper report using queryString we can call a procedure like this
example:
<![CDATA[{call PACKAGE.PROCEDURENAME($P{PARAM_NAME1},$P{PARAM_NAME2},$P{PARAM_NAME3},$P{PARAM_NAME4},$P{PARAM_NAME5},$P{PARAM_NAME6},$P{PARAM_NAME7},$P{OUT_PARAM_NAME8})}]]>
We can pass IN as well as OUT paramters and If you use cursor as out parameter and parameter class should be resultset(java.sql.ResultSet)
Related
I am following the steps outlined in the URL
https://community.ibm.com/community/user/hybriddatamanagement/viewdocument/generating-universally-unique-ident?CommunityKey=ea909850-39ea-4ac4-9512-8e2eb37ea09a&tab=librarydocuments to call Java UDF from DB2 database.
import java.util.UUID; // for UUID class
public class UUIDUDF
{
public static String randomUUID()
{
return UUID.randomUUID().toString();
}
}
I am able to generate JAR and I called
call sqlj.install_jar('file:///C:/Users/XXX/Desktop/UDF/UUIDUDF.jar', 'UUIDUDFJAR')
and I am able to find Jar being deployed at
"C:\ProgramData\IBM\DB2\DB2COPY1\function\jar\DB2ADMIN"
I restarted database manager using db2stop and db2start command..when i call the function I am getting error
"Java stored procedure or user-defined function
"DB2ADMIN.RANDOMUUID", specific name
"SQL200817125101637" could not load Java class
"C:\PROGRAMDATA\IBM\DB2\DB2COPY1", reason code
"".. SQLCODE=-4304, SQLSTATE=42724,
DRIVER=4.19.56"...
I created the function using below code
CREATE OR REPLACE FUNCTION RANDOMUUID()
RETURNS VARCHAR(36)
LANGUAGE JAVA
PARAMETER STYLE JAVA
NOT DETERMINISTIC NO EXTERNAL ACTION NO SQL
EXTERNAL NAME 'UUIDUDFJAR:UUIDUDF.randomUUID' ;
But when I generate DDL for my function in Db2 instance I am missing Jar reference in External name (EXTERNAL NAME 'UUIDUDF.randomUUID')
CREATE FUNCTION "DB2ADMIN"."RANDOMUUID" ()
RETURNS VARCHAR(36 OCTETS)
SPECIFIC "DB2ADMIN"."SQL200817125101637"
NO SQL
NO EXTERNAL ACTION
CALLED ON NULL INPUT
DISALLOW PARALLEL
LANGUAGE JAVA
EXTERNAL NAME 'UUIDUDF.randomUUID'
FENCED THREADSAFE
PARAMETER STYLE JAVA
NOT SECURED;
Could you please help me understand what i am missing here?
Thank you,
Pavan.
Actually I am executing my selenium test by reading test case data from excel.I wanted to fetch whether the test result is Passed or failed after execution of my first test case and write it in front of test case then y second test case and write it in front of test case and so on .
Before execution of my test case excelsheet screenshoot
http://i.stack.imgur.com/L2LNz.png
after execution of my test cases excelsheet screenshoot
http://i.stack.imgur.com/mMivW.png
You can fetch the results using TestNG. TestNG contains default listeners which reads if your test passed/failed/was skipped.
To set this data in excelsheet you need to create a class that implements from ITestListener
public class ExcelListener implements ITestListener
If you use any IDE, you should see a warning about need of creating unimplemented methods. Allow system to create them and you should see methods like
#Override
public void onTestSuccess(ITestResult result) {
// TODO Auto-generated method stub
}
Then all you have to code is
1. Open excel file
2. Find the right column
3. Insert status
To do that I recommend using Java Excel API.
To read existing excelsheet you need to provide absolute path, workbook name and a sheetname. Here's my code for method getExcel
public void getExcel(String filePath, String sheetName, String fileName) throws BiffException, IOException {
String absolutePath = filePath.concat("/").concat(fileName);
file = new FileInputStream(new File(absolutePath));
workbook = Workbook.getWorkbook(file);
worksheet = workbook.getSheet(sheetName);
}
After getting an excel file, you need to iterate through data.
You can provide exact column and row.
Hope it helps!
EDIT:
Place a listener like this
#Listeners(MyExcelListener.class)
public class MyTestClass {
}
I'm trying to use Enitity SQL to query data, but if the edmx file in another project, there will be an exception thrown. Below is my test steps.
Create a Class Library project and add an edmx file to it, create from database.
Create a Console Application, add the Class Library project to reference and copy the app.config file to this project.
Write the code as below
using (NorthwindEntities context = new NorthwindEntities())
{
string queryString = #"SELECT VALUE cus
FROM NorthwindEntities.Customers AS cus
WHERE cus.ID > 10";
ObjectQuery<Customers> cusQuery =
context.CreateQuery<Customers>(queryString);
List<Customers> cusList = cusQuery.ToList();
}
When I run the Console Application project, an exception is thrown: "'ID' is not a member of type 'NorthwindModel.Customers' in the currently loaded schemas."
It seems the schema doesn't loaded into the project, anyone has ideas?
Addional question: in this query, I select all the properties of this type, if I only select some of the properties, how to return an anonymous type of ObjectQuery?
Any suggestions are appreciate.
This is not an EF problem.
You have written the SQL statement by hand, you are not using the table definition that is in the EDMX file.
If you try to execute the SQL statement in the Query prompt of SQL Server, you will see that it fails there as well.
Try something like this:
var cus = from customers in context.Customers select customers;
var cusList = cus.ToList();
Greetings.
I have a parameter field in my crystal report called job. When i'm calling this report from web page, it prompts me for an input value ("Job1" or "Job2"). After i choose one, it displays in report. But when i try to export report to MS Word with
crystalReport.ExportToDisk(ExportFormatType.WordForWindows, "C:\\foo.doc");
i'm getting "Parameter value is missing" exception.
If i'm setting value manually with
crystalReport.SetParameterValue("job", value);
everything works fine, but i don't need to set a value manually. I want to use a value, chosen in crystal report prompt.
How can this be done?
Are you using a webform or a winform?
If you are using a webform make sure that you initialize ,load, set parameter of the reports on each postback.
private void ShowReport_click()
{
..do initializing,loading,provide logoninfo for data access, provide parameters
... show report
}
private void buttonExport_click()
{
ShowReport_click();
...Your Export Logic goes here
}
same can be applied to winforms too.
Based on a database myDB, I generate edmx for all table and compile the project. Then I create stored procedure myProc in myDB. Then I update the model by "Update Model from database" in the node Stored Procedure and add myProc. It is fine. Then "Create a function import" on myProc. It is fine. Then I compiled the project, it is fine.
The return type for this import function is scalars(string) because myProc return a string.
Then I want to use this function for this stored procedure, but I can find out the function.
How to find out the matching function and call it in code?
In EF 3.5 only functions that return Entities show up in ObjectServices.
I.e. importing pulls the Function into the Conceptual Model, but NOT into the code-generation.
We have addressed this problem in 4.0.
In the meantime you can call the function using eSQL.
i.e. something like this (pseudo code):
EntityConnection connection = ctx.Connection as EntityConnection;
//Open the connection if necessary
connection.Open()
//Create the command
EntityCommand command = new EntityCommand();
command.CommandText = "Function(#p1,#p2");
command.Parameters.Add(...);
command.Parameters.Add(...);
command.Connection = connection;
string s = command.ExecuteScalar().ToString();
Hope this helps
Alex