search
HomeDatabaseMysql TutorialiReport连接Mysql创建图表报表

iReport连接Mysql创建图表报表

Jun 07, 2016 pm 04:02 PM
ireportmysqloneenumeratecreatechartReportconnect

列举一下需要的资源: 1、mySql数据库安装好的 2、iReport+jasperreport配置好 3、我用的是Myeclipse,MySQL的驱动jar包不要忘记 第一部分:创建数据库连接 package com.mySqlsource;import java.sql.Connection;public class Database {private String dbUr

列举一下需要的资源:

1、mySql数据库安装好的

2、iReport+jasperreport配置好

3、我用的是Myeclipse,MySQL的驱动jar包不要忘记

第一部分:创建数据库连接

package com.mySqlsource;

import java.sql.Connection;

public class Database {
	private String dbUrl =  "jdbc:mysql://localhost:3306/bookdb";
	  private String dbUser="root";
	  private String dbPwd="123456";

	  public Database () throws Exception{
	     Class.forName("com.mysql.jdbc.Driver");
	  }

	  public Connection getConnection()throws Exception{
	      return java.sql.DriverManager.getConnection(dbUrl,dbUser,dbPwd);
	  }

	  public void closeConnection(Connection con){
	    try{
	        if(con!=null) con.close();
	      }catch(Exception e){
	        e.printStackTrace();
	      }
	  }
}
这个格式基本都一样的,其中bookdb是我新建数据库的名称,getConnection和closeConnection是两个操作开关,在使用的时候直接新建Database对象调用就好了。

第二部分:先看看我的数据库books表

\

打开iReport新建一张表不懂的话去看其他人的博客,很多的。在界面上找到数据源\打开进行如下选择

\

这个应该很简单的,设置完之后点击Test会提示测试成功,否则就是你的某些设置没做好,再重新检查一遍

打开组件面板找到\拖动到任意bands中,在iReport4.6.0中有一部分表格是有想到的,一部分没有,这个倒没关系了有的话一路next下去

没有的话直接完成后在图表上面右键选择chart data;点击Details,

\

这里是有默认名称的,双击默认名称打开属性设置界面

\

关于各个字段的意思及作用,我之前的文章有写到过,这里就不在赘述,有需要的话就翻翻前面的好了。

设置好之后,点击预览会出现如下情况

\

原因是在设计面板右侧图表的属性一栏,有一个属性Evaluation Time,大致意思就是什么时候进行更新数值,它默认是NOW

\

在这种情况下,只有你放在detail bands才会出现,但是它会出现很多次,不是我们想要的。将它设置为report就是在报表数据配置好之后进行更新,再次预览

\

第三部分:做好了这一步之后,对于可以连接数据库的人来说已经够了,但是如果想要通过web动态生成客户想要的报表呢,那么我们还是要通过网络连接数据库,之后再动态我们需要的模板

我使用Myeclipse+tomcat做的网站

package com.mySqlsource;

import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.sql.Connection;

import javax.servlet.ServletException;
import javax.servlet.http.*;
import net.sf.jasperreports.engine.JRExporterParameter;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.export.JRPdfExporter;
import net.sf.jasperreports.engine.util.JRLoader;

public class MySqlSource extends HttpServlet{


	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		doPost(req, resp);
	}


	public  void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		try{
			String root_path=this.getServletContext().getRealPath("/");
			root_path=root_path.replace("\\", "/");
			String file_path=root_path+"chart/test_char.jasper";
		
			Database data=new Database();	
			Connection con=data.getConnection();
			JasperReport report= (JasperReport)JRLoader.loadObject(file_path);
			JasperPrint print=JasperFillManager.fillReport(report, null, con);
			data.closeConnection(con);
			
			  OutputStream ouputStream = resp.getOutputStream();  
		        resp.setContentType("application/pdf");
		        resp.setCharacterEncoding("UTF-8");  
		        resp.setHeader("Content-Disposition", "attachment; filename=\""+ URLEncoder.encode("PDF报表", "UTF-8") + ".pdf\"");  
		            	
		        // 使用JRPdfExproter导出器导出pdf  
		        JRPdfExporter exporter = new JRPdfExporter();  
		        exporter.setParameter(JRExporterParameter.JASPER_PRINT, print);
		        exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, ouputStream);  
		        exporter.exportReport();
		        
		        
		        ouputStream.close();  
			
		}catch(Exception e){
			e.printStackTrace();
			
		}
	}
	
}
文件列表

 

\

test_char.jasper(本来想是test_chart.jasper后来发现创建时候少打了一个字母委屈)是iReport预览编译之后生成的,在你的创建目录中找得到

代码很简单,关键的几个函数:

JasperReport report= (JasperReport)JRLoader.loadObject(file_path);
JasperPrint print=JasperFillManager.fillReport(report, null, con);
<pre name="code" class="html"> JRPdfExporter exporter = new JRPdfExporter();  
exporter.setParameter(JRExporterParameter.JASPER_PRINT, print);
exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, ouputStream);  
这几个函数在之前的文章中也提到过,所以不再啰嗦。
特别注意:要将jasperreport的lib文件最好是都放到web项目的WEB-INF/lib目录下,生的报错
如果需要源码,留邮箱,希望能共同探讨
Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Explain the role of InnoDB redo logs and undo logs.Explain the role of InnoDB redo logs and undo logs.Apr 15, 2025 am 12:16 AM

InnoDB uses redologs and undologs to ensure data consistency and reliability. 1.redologs record data page modification to ensure crash recovery and transaction persistence. 2.undologs records the original data value and supports transaction rollback and MVCC.

What are the key metrics to look for in an EXPLAIN output (type, key, rows, Extra)?What are the key metrics to look for in an EXPLAIN output (type, key, rows, Extra)?Apr 15, 2025 am 12:15 AM

Key metrics for EXPLAIN commands include type, key, rows, and Extra. 1) The type reflects the access type of the query. The higher the value, the higher the efficiency, such as const is better than ALL. 2) The key displays the index used, and NULL indicates no index. 3) rows estimates the number of scanned rows, affecting query performance. 4) Extra provides additional information, such as Usingfilesort prompts that it needs to be optimized.

What is the Using temporary status in EXPLAIN and how to avoid it?What is the Using temporary status in EXPLAIN and how to avoid it?Apr 15, 2025 am 12:14 AM

Usingtemporary indicates that the need to create temporary tables in MySQL queries, which are commonly found in ORDERBY using DISTINCT, GROUPBY, or non-indexed columns. You can avoid the occurrence of indexes and rewrite queries and improve query performance. Specifically, when Usingtemporary appears in EXPLAIN output, it means that MySQL needs to create temporary tables to handle queries. This usually occurs when: 1) deduplication or grouping when using DISTINCT or GROUPBY; 2) sort when ORDERBY contains non-index columns; 3) use complex subquery or join operations. Optimization methods include: 1) ORDERBY and GROUPB

Describe the different SQL transaction isolation levels (Read Uncommitted, Read Committed, Repeatable Read, Serializable) and their implications in MySQL/InnoDB.Describe the different SQL transaction isolation levels (Read Uncommitted, Read Committed, Repeatable Read, Serializable) and their implications in MySQL/InnoDB.Apr 15, 2025 am 12:11 AM

MySQL/InnoDB supports four transaction isolation levels: ReadUncommitted, ReadCommitted, RepeatableRead and Serializable. 1.ReadUncommitted allows reading of uncommitted data, which may cause dirty reading. 2. ReadCommitted avoids dirty reading, but non-repeatable reading may occur. 3.RepeatableRead is the default level, avoiding dirty reading and non-repeatable reading, but phantom reading may occur. 4. Serializable avoids all concurrency problems but reduces concurrency. Choosing the appropriate isolation level requires balancing data consistency and performance requirements.

MySQL vs. Other Databases: Comparing the OptionsMySQL vs. Other Databases: Comparing the OptionsApr 15, 2025 am 12:08 AM

MySQL is suitable for web applications and content management systems and is popular for its open source, high performance and ease of use. 1) Compared with PostgreSQL, MySQL performs better in simple queries and high concurrent read operations. 2) Compared with Oracle, MySQL is more popular among small and medium-sized enterprises because of its open source and low cost. 3) Compared with Microsoft SQL Server, MySQL is more suitable for cross-platform applications. 4) Unlike MongoDB, MySQL is more suitable for structured data and transaction processing.

How does MySQL index cardinality affect query performance?How does MySQL index cardinality affect query performance?Apr 14, 2025 am 12:18 AM

MySQL index cardinality has a significant impact on query performance: 1. High cardinality index can more effectively narrow the data range and improve query efficiency; 2. Low cardinality index may lead to full table scanning and reduce query performance; 3. In joint index, high cardinality sequences should be placed in front to optimize query.

MySQL: Resources and Tutorials for New UsersMySQL: Resources and Tutorials for New UsersApr 14, 2025 am 12:16 AM

The MySQL learning path includes basic knowledge, core concepts, usage examples, and optimization techniques. 1) Understand basic concepts such as tables, rows, columns, and SQL queries. 2) Learn the definition, working principles and advantages of MySQL. 3) Master basic CRUD operations and advanced usage, such as indexes and stored procedures. 4) Familiar with common error debugging and performance optimization suggestions, such as rational use of indexes and optimization queries. Through these steps, you will have a full grasp of the use and optimization of MySQL.

Real-World MySQL: Examples and Use CasesReal-World MySQL: Examples and Use CasesApr 14, 2025 am 12:15 AM

MySQL's real-world applications include basic database design and complex query optimization. 1) Basic usage: used to store and manage user data, such as inserting, querying, updating and deleting user information. 2) Advanced usage: Handle complex business logic, such as order and inventory management of e-commerce platforms. 3) Performance optimization: Improve performance by rationally using indexes, partition tables and query caches.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.