Jasper report (2)---using JDBC as the data source

Source: Internet
Author: User

Use JDBC as the data source for Jasper report to connect to the database to read data

  1. To create a new Java project in Eclipse (process slightly), the structure of my Java project is as follows:

  

  Note: The jar package for spring here is not necessary for the project to run, it is the package I used when I use JavaBean as the data source, please ignore.

  2. Connect the database code (I am connected to a MySQL database)

1  Packagecom.report.sample;2 3 Importjava.sql.Connection;4 ImportJava.sql.DriverManager;5 Importjava.sql.SQLException;6 7  Public classConnectionProvider {8     Private StaticString driverclassname = "Com.mysql.jdbc.Driver";9     Private StaticString username= "Root";Ten     Private StaticString password= "Root"; One     Private StaticString url= "Jdbc:mysql://localhost/test"; A      -     Static{ -         Try { the Class.forName (driverclassname); -}Catch(ClassNotFoundException e) { -             Throw NewRuntimeException (e); -         } +     } -      +      Public StaticConnection getconnection () { A         Try { at             returndrivermanager.getconnection (URL, username, password); -}Catch(SQLException e) { -             Throw NewRuntimeException (e); -         } -     } -}

  3. Get the path where the compiled. Jasper file is located (for. Jrxml compiled into a. jasper file I'll write it alone)

1  Packagecom.report.sample;2 3 Importjava.io.IOException;4 5  Public classGetPath {6     7       PublicString Showurl ()throwsIOException {8          return  This. GetClass (). GetResource ("/"). GetPath ();9      }Ten}

  4. Connect the data source, display the data read from the database to the PDF and save it in the same directory as the. jasper file (you can output HTML, Excel, PDF in a variety of forms, I will be in another chapter in detail)

1  Packagecom.report.sample;2 3 ImportJava.io.File;4 ImportJava.io.FileOutputStream;5 Importjava.io.IOException;6 Importjava.sql.Connection;7 ImportJava.util.HashMap;8 ImportJava.util.Map;9 Ten Importnet.sf.jasperreports.engine.JRException; One ImportNet.sf.jasperreports.engine.JasperRunManager; A  -  Public classJrwithjdbcdatasource { -        the      Public Static voidMain (string[] args)throwsexception{ -map<string, object> parameters =NewHashmap<string,object>();  -Connection Connection =connectionprovider.getconnection (); -Generatepdfreport (NewGetPath (). Showurl (), parameters, connection); +     }  -      +     Private Static voidGeneratepdfreport (String path, map<string, object>parameters, Connection Connection) { A         Try { at             byte[] Pdfstream = jasperrunmanager.runreporttopdf (path + "/dbreport.jasper"), parameters, connection); -File File =NewFile (path + "/report.pdf")); -FileOutputStream op =Newfileoutputstream (file); - Op.write (pdfstream); - Op.flush (); - op.close (); in}Catch(IOException e) { - e.printstacktrace (); to}Catch(jrexception e) { + e.printstacktrace (); -         } the     } *}

  5. Create a new directory in the project to hold the report template file that was designed (my new folder is "res"), then right-click the new Jasper Report as shown in the steps

  

Continue to choose the template that you want to design the report to use, as you choose, I choose the Blank_a4_landscape

  

Then select the directory you want to save, select the directory you created to save the template file, and name the file, I chose the "res" directory, Dbreport1.xml

  

Select the data source, here I choose "Database JDBC Connect"

  

To set information about a JDBC data source connection

  

  Note: Here I'm experimenting with the T_employee and V views in the test database, and the result is that we can read the data from both the table and the view

  

See the interface that shows that our JDBC connection has been created successfully to access the database properly

  

6. Use Jasper Studio to design our report template (about how to design the template, I will explain in another article, because more content, I will simply design too complex I have not come and to learn)

  

  Select TextField and then double-click the interface that appears, followed by our Java syntax

  

Click Save, our template has a field: name, I also added a field here is salary

7. Important part of the database also forget to tell everyone, here I was simply created a test database inside a table T_employee, there is a view V, create the following statement:

A) Create a database

1 CREATE DATABASE ' test '

  b) CREATE TABLE T_employee

CREATE TABLE' T_employee ' (' ID ')int( One) not NULL, ' name 'varchar( $)DEFAULT NULL, ' age 'varchar( $)DEFAULT NULL, ' salary 'int( One)DEFAULT NULL, ' address 'varchar( $)DEFAULT NULL,  PRIMARY KEY(' id ')) ENGINE=InnoDBDEFAULTCHARSET=UTF8;

  c) Create a view V (creating a view here is not necessary, just to do the experiment to show that the data source can be more than just a table or a view)

Create View  as Select  from T_employee;

  8. At this point, we can go to run, the main method inside the Jrwithjdbcdatasource class to test whether our process is correct, if a. pdf file is generated in the bin directory of your project, the creation is successful

Because the experiment I'm doing here is generating PDF files, so the format of the PDF is generated, and the output path can be defined by itself. JDBC as the data source to read the values in the database is shown in the experiment above the PDF to the end.

  

  

Jasper report (2)---using JDBC as the data source

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.