Search code examples
javajasper-reports

How to pass a value to an sql Query to generate a jasper Report


still a noob here I really need help with something.

I have a jasper report that I want to generate in my java program, which is displaying information retrieved from mysql database.

I have a query like this as an example:

String query = "SELECT * FROM users where city = ?";

In generating a jasper report, when i pass that sql query with a specific value like city= "Washington", it retrieves the information that i want.

But what I would want to do is for that city string value to be passed from the java code as a parameter to my sql query so that it retrieves information based on the city name that I specify in my java code.

Is there a way i can do it, if yes can I have an example please. Hopefully i have tried to explain in a manner that is understandable

Will appreciate all the help that I can get.

<subDataset name="userDataset" uuid="b277feac-f289-4d08-83ad-06eb2f992cb7">
        <property name="com.jaspersoft.studio.data.sql.tables" value=""/>
        <property name="com.jaspersoft.studio.data.defaultdataadapter" value="userAdapater"/>
        <queryString language="SQL">
            <![CDATA[SELECT * FROM users where city = (THIS IS THE VALUE I WANT TO PASS AS A PARAMETER FROM JAVA JODE THAT WILL GENERATE THE REPORT)]]>

Solution

  • you can define a string field in to your jrxml file and map it from your java code with a java String field, following these steps:

    define a String parameter in the jrxml file:

    <parameter name="cityParam" class="java.lang.String"/>
    

    and in your java code, add this map :

    String cityName = "Washington"; // The value you want to pass as the city name
    Map<String, Object> map = new HashMap<>();
    map.put("cityParam", cityName);
    
    JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, map, yourDataSource);