问题
Is it possible to execute "insert query" in IReports/jasper reports during report generation?
回答1:
Yes, the idea you need is parameters using this syntax: $P!{PARAM_NAME}.
So your entire SQL query (or other type of query) could be simply $P!{SQL}. Then you pass in exactly the dynamic SQL that you need.
UPDATE: After reading Sharad's comment, I realized that my answer above is not good. What I wrote is true... but it fails to address the core question.
No, your report cannot really execute an insert statement. Strictly speaking, I'm sure it's not impossible. You could add a scriptlet or custom function in a .jar file that makes a connection and does an insert. But realistically speaking... a report will execute one or more queries. The JR framework is not intended to execute inserts or updates.
回答2:
Yes you can. You can execute the query when you want to display the report. Here is a sample that works for me.
try {
Map parameters = new HashMap();
connectionString ="jdbc:mysql://localhost/myDb", "myUsername", "myPassword"
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection(connectionString);
PreparedStatement stmt = conn.prepareStatement(query);
ResultSet rs = stmt.executeQuery();
JRResultSetDataSource rsdt = new JRResultSetDataSource(rs);
JasperPrint jp;
jp = JasperFillManager.fillReport("sourceFileName.jasper", parameters, rsdt);
JasperViewer jv = new JasperViewer(jp, false);
jv.setVisible(true);
} catch (ClassNotFoundException | SQLException | JRException ex) {
ex.printStackTrace();
}
来源:https://stackoverflow.com/questions/7712296/insert-query-in-jasper-reports