Search code examples
javajasper-reports

Retrieve second result from query with parameter in JasperReport


I have code for JasperReport:

        int id = 1;
        String sql = "SELECT * FROM invoices where id = '"+ id + "'";
        InputStream source = getClass().getClassLoader().getResourceAsStream("tre/"+ reportName + ".jrxml");
        JasperDesign jd = JRXmlLoader.load(source);
        JRDesignQuery newQuery = new JRDesignQuery();
        newQuery.setText(sql);
        jd.setQuery(newQuery);
        JasperReport jr = JasperCompileManager.compileReport(jd);
        JasperPrint jp = JasperFillManager.fillReport(jr, null, ConnectionToDb.connectDb());
        JasperViewer.viewReport(jp);

So far so good. This bring me in the report exactly number of rows for current invoice. Now how I can add Fields in JasperReport, which will contains the detail info from both company for the invoice using SQL again and the query is come from java code in method? Let's say this query:

        String company = textField.getText();
        String sql = "SELECT * FROM companies where name = '"+ company + "'";

here is the part of JasperReport:

<queryString>
    <![CDATA[select * from invoices]]>
</queryString>
<field name="Name" class="java.lang.Object"/>
<field name="Type" class="java.lang.Object"/>
<field name="Quantity" class="java.lang.Object"/>
<field name="Price" class="java.lang.Object"/>
<field name="Info" class="java.lang.Object"/>

P.S. The query in the report I'm override it with newQuery.setText(sql);


Solution

  • Map<String, Object> param = new HashMap<String, Object>();
    ......          
    JasperPrint jp = JasperFillManager.fillReport(jr, param, ConnectionToDb.connectDb());
    

    Then in JasperReport: Parameters with pattern: $P{nameCompany}