Home Database Mysql Tutorial iReport连接Mysql创建图表报表

iReport连接Mysql创建图表报表

Jun 07, 2016 pm 04:02 PM
ireport mysql one enumerate create chart Report connect

列举一下需要的资源: 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();
	      }
	  }
}
Copy after login
这个格式基本都一样的,其中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();
			
		}
	}
	
}
Copy after login
文件列表

\

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);  
Copy after login
这几个函数在之前的文章中也提到过,所以不再啰嗦。
特别注意:要将jasperreport的lib文件最好是都放到web项目的WEB-INF/lib目录下,生的报错
如果需要源码,留邮箱,希望能共同探讨
Statement of this Website
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

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

MySQL: An Introduction to the World's Most Popular Database MySQL: An Introduction to the World's Most Popular Database Apr 12, 2025 am 12:18 AM

MySQL is an open source relational database management system, mainly used to store and retrieve data quickly and reliably. Its working principle includes client requests, query resolution, execution of queries and return results. Examples of usage include creating tables, inserting and querying data, and advanced features such as JOIN operations. Common errors involve SQL syntax, data types, and permissions, and optimization suggestions include the use of indexes, optimized queries, and partitioning of tables.

How to open phpmyadmin How to open phpmyadmin Apr 10, 2025 pm 10:51 PM

You can open phpMyAdmin through the following steps: 1. Log in to the website control panel; 2. Find and click the phpMyAdmin icon; 3. Enter MySQL credentials; 4. Click "Login".

Why Use MySQL? Benefits and Advantages Why Use MySQL? Benefits and Advantages Apr 12, 2025 am 12:17 AM

MySQL is chosen for its performance, reliability, ease of use, and community support. 1.MySQL provides efficient data storage and retrieval functions, supporting multiple data types and advanced query operations. 2. Adopt client-server architecture and multiple storage engines to support transaction and query optimization. 3. Easy to use, supports a variety of operating systems and programming languages. 4. Have strong community support and provide rich resources and solutions.

MySQL's Place: Databases and Programming MySQL's Place: Databases and Programming Apr 13, 2025 am 12:18 AM

MySQL's position in databases and programming is very important. It is an open source relational database management system that is widely used in various application scenarios. 1) MySQL provides efficient data storage, organization and retrieval functions, supporting Web, mobile and enterprise-level systems. 2) It uses a client-server architecture, supports multiple storage engines and index optimization. 3) Basic usages include creating tables and inserting data, and advanced usages involve multi-table JOINs and complex queries. 4) Frequently asked questions such as SQL syntax errors and performance issues can be debugged through the EXPLAIN command and slow query log. 5) Performance optimization methods include rational use of indexes, optimized query and use of caches. Best practices include using transactions and PreparedStatemen

How to connect to the database of apache How to connect to the database of apache Apr 13, 2025 pm 01:03 PM

Apache connects to a database requires the following steps: Install the database driver. Configure the web.xml file to create a connection pool. Create a JDBC data source and specify the connection settings. Use the JDBC API to access the database from Java code, including getting connections, creating statements, binding parameters, executing queries or updates, and processing results.

How to start mysql by docker How to start mysql by docker Apr 15, 2025 pm 12:09 PM

The process of starting MySQL in Docker consists of the following steps: Pull the MySQL image to create and start the container, set the root user password, and map the port verification connection Create the database and the user grants all permissions to the database

MySQL's Role: Databases in Web Applications MySQL's Role: Databases in Web Applications Apr 17, 2025 am 12:23 AM

The main role of MySQL in web applications is to store and manage data. 1.MySQL efficiently processes user information, product catalogs, transaction records and other data. 2. Through SQL query, developers can extract information from the database to generate dynamic content. 3.MySQL works based on the client-server model to ensure acceptable query speed.

How to install mysql in centos7 How to install mysql in centos7 Apr 14, 2025 pm 08:30 PM

The key to installing MySQL elegantly is to add the official MySQL repository. The specific steps are as follows: Download the MySQL official GPG key to prevent phishing attacks. Add MySQL repository file: rpm -Uvh https://dev.mysql.com/get/mysql80-community-release-el7-3.noarch.rpm Update yum repository cache: yum update installation MySQL: yum install mysql-server startup MySQL service: systemctl start mysqld set up booting

See all articles