0% found this document useful (0 votes)
8 views

Database Reporting

Uploaded by

Isuri Gunarathne
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

Database Reporting

Uploaded by

Isuri Gunarathne
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 48

Enterprise Application Development 1

By Dr. Randima Dinalankara


[email protected]
Main topics - Today
• Language Fundamentals
• Object Oriented Programming
• Interface & Packaging
• GUI and Event handling
• Exception Handling
• Database Programming and Reporting
• String & IO handling
• Generics and Collections
• Lambda & Stream
• Multithreading Programming
• Design Patterns
Java Database Management
JDBC
• JDBC - Java Database Connection
• It is an API (Application Programming Interface).
• It connects to Database and executes queries.
JDBC API
• ODBC was used before JDBC
• ODBC uses C language and not secure
• Therefore, java introduced more secured JDBC

• JDBC API activities


– Connecting to the database
– Execute queries and update statements
– Retrieve results
Components of JDBC API
• There are five components provided by the JDBC API
1. Drivers

2. Driver Manager

3. Connection

4. Statement

5. Result Set
JDBC Drivers
• Driver handles the communication between database and the
application.

• JDBC uses four (04) drivers


– JDBC-ODBC bridge driver
– Native Driver
– Network Protocol Driver
– Thin Driver

• Driver manager manages the different drivers.


JDBC Drivers
JDBC-ODBC Driver
• Convert all the JDBC calls to ODBC calls and send them to ODBC
driver
Native API Driver
• Convert JDBC calls into database-specific calls i.e. this driver is
specific to a database
Network Protocol Driver
• Requests are passed through the network to the middle-tier server.
• The middle-tier then translates the request to the database.
Thin Driver
• This driver converts JDBC calls directly into the vendor specific
database protocol.
Connection

• The connection interface represents a session with the database

connection provided by the driver.


Java DB Statement

• A statement is the vehicle for sending SQL queries to the

database and retrieving a set of results.

• Statements can be SQL inserts, updates, deletes or other queries.


Java DB Prepared Statement

• Pre complied SQL statement

• Most suitable for repeating SQL execution

• To use prepared statement, create it using


method

• Useful if the statement is run on for loop or while loop.

• Will reduce execution time.


Result Set

• The ResultSet interface defines methods for accessing tables of

data generated as the result of executing a statement.


Connecting with MYSQL
Windows Environment
Before testing JDBC with MySQL
• Setup a server in local machine
– WAMP
– XAMPP
• Create a database in MySQL
• Create tables in the database.
• Setup authentication
– Username
– Password
• Run the MySQL Server
Five steps in JDBC connection

1. Register the class

2. Create

3. Create

4. Execute the Queries

5. Close the connection


Five steps in JDBC connection
Step 1 a: Download the driver from
https://dev.mysql.com/downloads/connector/j/

Step 1 b: Unzip and extract the content

Step 1 c: Copy paste the <connector- >.jar file to


C:\Program Files\Java\jdk-<ver>\jre\lib\ext and
C:\Program Files\Java\jre-<ver>\jre\lib\ext
Five steps in JDBC connection
Step 1 d: Register the Driver
• Use to register the driver

Class.forName(“<driver class name>”);

possible exception - ClassNotFoundException


Five steps in JDBC connection
Step 2: Create a connection

possible exception - SQLException


Five steps in JDBC connection
Step 3: Create a Statement object

possible exception - SQLException


Five steps in JDBC connection
Step 4: Execute the Query

Use iterating mechanism to display the results in resultObj

possible exception - SQLException


Five steps in JDBC connection
Step 5: Close the connection

possible exception - SQLException


Example
A database with a table was created and MySQL server is running.
Database : testdb
Username : user1234
Password : Pass@1234
Table : Vegetables
ID (int) - primary
Name(varchar-32)
Price (float)
import java.sql.*;
public class Database1 {
static final String QUERY = "Select * from Vegetables";
public static void main(String[] args) {
try{
Class.forName("com.mysql.cj.jdbc.Driver");
Connection conn =
DriverManager.getConnection("jdbc:mysql://localhost/testdb",
"user1234","Pass@1234");
Statement stat = conn.createStatement();
ResultSet result = stat.executeQuery(QUERY);
while(result.next())
System.out.print(result.getInt("ID")+"\t"result.getString("Name
")+"\tRs."+result.getFloat("Price"));
conn.close();
}catch(Exception e){
System.out.println("Exception occured >>> "+e);
}
Simple GUI to check the connectivity
• Please refer the Lesson 6 Example 2.

• Simply apply the database name, user name, and password to


check the connectivity.
Simple GUI displaying table data
• Please refer the Lesson 6 Example 3.

• The connection details are already stored to constants and extract


details from pre-selected table.
GUI to display tables dynamically
• Example 4
• This is an advanced GUI, where the available tables are first
displayed.
• Then the user can select which table data should be viewed in the
table area.
• The number of columns for the table will be dynamically allocated
and display all the data in the selected table.

• Excessive use of Metadata of the table.


DB and CRUD (CReate, Update, Delete)
CRUD

Lesson 6/ Example 6
Prepared Statements
• Lets look at the order of the regular query execution.
– Class.forName("com.mysql.cj.jdbc.Driver");
– Connection conn = DriverManager.getConnection(dbURL, dbUser,
dbPass);

– Statement stat = conn.createStatement();

– ResultSet result = stat.executeQuery(QUERY);

– conn.close();
Prepared Statements (cont.)
• This mechanism is not efficient if the query needs to be run
repeately with different parameters.

• The query building process will be time consuming.

• Therefore, more dynamic and faster Prepared Statements can


be used.
Prepared Statements (cont.)
• Steps in creating Prepared Statement
– Class.forName("com.mysql.cj.jdbc.Driver");
– Connection conn = DriverManager.getConnection(dbURL, dbUser,
dbPass);

– PreparedStatement preStat = conn.preparedStatement(QUERY);

– preStat.set<DataType>(<index>,<variable/value>);

– preStat.executeUpdate();

– conn.close();
Prepared Statement Example
String pQuery = “insert into vegetables
(Name,Price,Quantity) values(?,?,?);

PreparedStatement pStat = conn.PreparedStatement(pQuery);


pStat.setString(1,”Carrot”);
pStat.setFloat(2,256.25);
pStat.setInt(67);
pStat.executeUpdate();
Prepared Statement Use
• Discuss the examples in the class
Reporting
Report
• Representation of data and information in a meaningful format for
the reader.

• It can be a summary of information or descriptive.


Common Report Template
• Title
• Page Header
• Page Footer
• Details
• Summary
• Column Header
• Column Footer
Get familiar with Jasper Reporting
• Tutorial
tutorialsPoint JasperReport Tutorial
https://www.tutorialspoint.com/jasper_reports/index.htm#:~:text=J
asperReports%20is%20an%20open%20source,that%20a%20begin
ner%20should%20know.
Advantages of Jasper Report
• Can represents both text and graphical content.
• Flexible report templates
• Can supply data in multiple ways
• Can import from multiple sources
• Can export in different formats
• Can impose watermark
Jasper Report
• First, download Jasper Studio.

• Create a template file (jrxml) using Jasper Studio.


– Create DB Connection
– Add jar file of the connection
– Provide user credentials
– Once the template is open, drag and drop the static and text fields
appropriately to create the basic tabular output.

• Use the preview tab to view the output of the report.


Jasper Report (cont.)
• Open Maven Project
• Add the
– jasperreports,
– jasperreports-fonts,
– and jasperreports-javaflow to the Dependancies.
– The dependancies can be downloaded by the NetBeans automatically or
you can manually download and provide the path of the jar files.

• Consider the report was created to retrieve data related to a table


in testdb data base. Then, add the code to the action performed
function of the button as mentioned in the next slide.
try{
Class.forName("com.mysql.cj.jdbc.Driver");
Connection conn = DriverManager.getConnection(dbURL,usr,pass);
String reportPath = "<path>\\Report.jrxml";
JasperReport jr = JasperCompileManager.compileReport(reportPath);
JasperPrint jp = JasperFillManager.fillReport(jr, null,conn);

JasperViewer.viewReport(jp);
conn.close();
} catch (SQLException| ClassNotFoundException e) {
JOptionPane.showMessageDialog(null, e.getMessage());
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e.getMessage());
}

Lesson 6/Example 5
Take home assignment
• Watch this YouTube tutorial on setting up Jasper Studio and
Jasper Reports.
– Create and Print Reports in Netbeans 16 using JasperReport with MySQL
Server Database - Java Maven
– https://www.youtube.com/watch?v=NlPpeLVbysA

• Build and configure report generator accordingly.


• Create Jasper Report

• File > New > Jasper Report


• Select Blank_A4 > Click on next
• Select MyReports >, Provide name to the file, and Click on next
• Select New button in data source window.
• Select Database JDBC Connection
– Select MYSQL connection from the list
– Set the URL with proper database (mysql:jdbc://localhost/<database name>)
– Provide Login credentials to login to the database.
Practice Problems
• Name the five (05) components of JDBC.
• Write a statement to register the driver “mytestdriver.abc.jdbc” in
the project.
• A prepared statement ‘pStat’ is with a query “update members set
fname=?, salary=? where id=?”. Write down statements to assign
“David”, 26358.57, and 254 to fname, salary, and id, respectively.
Use appropriate data types.
• Compare thin driver against native driver.
• Why did java introduce JDBC-ODBC driver?

You might also like