0% found this document useful (0 votes)
27 views42 pages

Databases Concepts

database

Uploaded by

aliza
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
27 views42 pages

Databases Concepts

database

Uploaded by

aliza
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 42

Databases:

 A relational database uses tables to store and manipulate data.


 Each table contains one or more records, or rows, that contain the data for a single
entry.
 Each row contains one or more fields, or columns, with each column representing
a single item of data.
 Most tables contain a primary key that uniquely identifies each row in the table.
 The software that manages a relational database is called a database management
system (DBMS).
 Four of the most popular database management systems today are Oracle,
Microsoft SQL Server, IBM’s DB2, and Microsoft Access.
 The tables in a relational database are related to each other through their key
fields.
 For example, the BookCode field is used to relate the Books and BookOrders
tables. The BookCode field in the BookOrders table is called a foreign key
because it identifies a related row in the Books table.
 Three types of relationships can exist between tables. The most common type is a
one-to-many relationship as illustrated above. However, two tables can also have
a one-to-one relationship or a many-to-many relationship.
 A database management system requires a name and data type for each
field.Depending on the data type, you may be able to specify other attributes for
the field such as field size, a value to be used as a label, whether the field is
required by newrows or not, and so on.
 If you specify a default value for a field, that value is used for the field in a new
record when no other value is supplied

How to access a database with Java


 Before an application can use JDBC (Java Database Connectivity) to manipulate
the data in a database, you need to connect the application to the database.
 The Java application uses the JDBC driver manager to load a database driver.
Then, the Java application can use one or more of the driver types to connect to
the database and manipulate the data.
 JDBC-ODBC bridge driver to connect to a database through ODBC (Open
 Database Connectivity), which is a standard way to access databases that were
developed by Microsoft. Since ODBC drivers exist for most modern databases,
 JDBC-ODBC bridge driver provides a way to connect Java with almost any
database type. And this driver is included as a part of the Java.

 A JDBC-ODBC bridge driver converts JDBC calls into ODBC


calls that access the DBMS protocol. This data access method
requires that the ODBC drivers be installed on the client machines
 To get information about the drivers that are currently available,
check the Java web site at www.java.sun.com/products/jdbc
and click on the List of Drivers Available link.

How to connect to a database

There are following six steps involved in building a JDBC application −


 Import the packages: Requires that you include the packages containing the
JDBC classes needed for database programming. Most often, using import
java.sql.* will suffice.
 we need the MySQL Connector/J driver. If you are using NetBeans IDE, than
you have already the driver at hand. Inside the Projects tab, right click on the
Libraries node and select Add Library option. From the list of options, select
MySQL JDBC Driver.


Figure: NetBeans project libs
 Register the JDBC driver: Requires that you initialize a driver so you can open
a communication channel with the database.
To start, we use the forName method of the Class class to load the driver.

For MySQl:

Class.forName("com.mysql.jdbc.Driver");

For Derby Db:

Class.forName("org.apache.derby.jdbc.ClientDriver");

 Open a connection: Requires using.


Then, the getConnection method of the DriverManager class to return a
connection object.
i.e
 The DriverManager.getConnection() method to create a Connection object,
which represents a physical connection with the database.
To do that, we must supply a URL for the database, a user name, and a password.
The URL for these drivers starts with “jdbc”. Then, for JDBC-ODBC bridge
drivers, the subprotocol is “odbc or mysql or derby ” and the database URL is the
name that you used when you configured your database.
jdbc:<subprotool>:databasename

i.e

DriverManager.getConnection("jdbc:mysql://hostname:port/dbname","username", "password");

For MySQl:

DriverManager.getConnection("jdbc:mysql://localhost:3306/dbname","username", "password");

For Built In Derby Db:


DriverManager.getConnection("jdbc:derby://localhost:1527/Registration","laila", "123");

 Execute a query: Requires using an object of type Statement for building and
submitting an SQL statement to the database.

Statement stmt = conn.createStatement();


String sql;
sql = "SELECT id, first, last, age FROM Employees";
ResultSet rs = stmt.executeQuery(sql);

 Extract data from result set: Requires that you use the
appropriateResultSet.getXXX() method to retrieve the data from the result set.

while(rs.next()){
//Retrieve by column name
int id = rs.getInt("id");
int age = rs.getInt("age");
String first = rs.getString("first");
String last = rs.getString("last");

 Clean up the environment: Requires explicitly closing all database resources


versus relying on the JVM's garbage collection.

rs.close();
stmt.close();
conn.close();
EXAMPLE: Create a Frame for Contacts Table

In the following example, the default user name and password for mySql database.
 The security for the database was enabled, you would need to supply a valid user
name and password for the database.

Code for Connect :


//load the JDBC-ODBC bridge driver
//use the DriverManager to create a Connection object
try{
// Class.forName("org.apache.derby.jdbc.ClientDriver");
Class.forName("com.mysql.jdbc.Driver");
// String myDb = "jdbc:derby://localhost:1527/AddressBook";
String myDb =
"jdbc:mysql://localhost:3306/addressbook?zeroDateTimeBehavior=convertT
oNull";

DBconn = DriverManager.getConnection(myDb,"root","");
jTextArea1.setText("Db connected");
statement =
DBconn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONC
UR_UPDATABLE);
save.setEnabled(false);
cancel.setEnabled(false);String user = "root";

Code for GetData


 Once you connect to a database, you’re ready to retrieve data from the database
and to manipulate that data.
String num = "";
String address = "";
String name="";
String email="";

try{
String query = "SELECT * FROM contacts";
results = statement.executeQuery(query);
rows= results.getRow();

//output the resultset data


if(results.first()){
name = results.getString(1);
address = results.getString(2);

num = results.getString(4);
email = results.getString(3);
System.out.println(email);
nameText.setText(name);
addressText.setText(address);
phoneTxt.setText(num);
emailTxt.setText(email);
}
}catch(Exception e){e.printStackTrace();}
How to return a result set

 The createStatement method is called from a Connection object to return a


Statement object.
 Then, the executeQuery method is called from the Statement object to execute
an SQL SELECT statement that’s coded as a string. Since this SELECT statement
only identifies a single record (the book with the book code equal to WARP), this
result set will be a table that contains only one row. This type of query lets a user
search for a book by its book code.

Statement statement = connection.createStatement(ResultSet.


TYPE_SCROLL_SENSITIVE, ResultSet.Concur_Update);
// These Constants are provide so that we can scroll result set easily and any update in
the data will be reflected

The result of a SQL query is available in Resultset object. Resultsets are of 3 types.

Type Description

ResultSet.TYPE_FORWARD_ONLY The cursor can only move forward in the result set.

ResultSet.TYPE_SCROLL_INSENSITIVE The cursor can scroll forward and backward, and


the result set is not sensitive to changes made by
others to the database that occur after the result set
was created.

ResultSet.TYPE_SCROLL_SENSITIVE. The cursor can scroll forward and backward, and


the result set is sensitive to changes made by others
to the database that occur after the result set was
created.

Concurrency of ResultSet
By default get one that is CONCUR_READ_ONLY.

Concurrency Description

ResultSet.CONCUR_READ_ONLY Creates a read-only result set. This is the default

ResultSet.CONCUR_UPDATABLE Creates an updateable result set.

ResultSet results = statement.executeQuery( "SELECT * FROM contacts");


rows= results.getRow();

 The createStatement method of a Connection object creates a Statement object.


 Then, the executeQuery method of the Statement object executes a SELECT
statement that returns a ResultSet object.
 By default, the createStatement method creates a forward-only, read-only result
set.
 However, you can set the type and concurrency of a Statement object by coding
the constants above for the two arguments of the createStatement method.
 Both the createStatement and executeQuery methods throw an exception of
theSQLException type. As a result, any code that returns a result set will need to
catch or throw this exception.
How to move the cursor through a result set

Code examples

Coding for Next Record.


String name="";
String address="";
String email="";
String num="";
try{ if(!results.isLast()){
results.next();
name = results.getString(1);
address = results.getString(2);
System.out.println(name);
num = results.getString(3);
email = results.getString(4);
nameText.setText(name);
addressText.setText(address);
phoneTxt.setText(num);
emailTxt.setText(email);
}} catch(SQLException e){e.printStackTrace();}

Code for Last record :

results.last();
name = results.getString(1);
address = results.getString(2);
System.out.println(name);
num = results.getString(3);
email = results.getString(4);
nameText.setText(name);
addressText.setText(address);
phoneTxt.setText(num);
emailTxt.setText(email);

Code for Previous Record

String name="";
String address="";
String email="";
String num="";
try{
if(!results.isFirst()){
results.previous();
name = results.getString(1);
address = results.getString(2);
System.out.println(name);
num = results.getString(3);
email = results.getString(4);
nameText.setText(name);
addressText.setText(address);
phoneTxt.setText(num);
emailTxt.setText(email);
}} catch(SQLException e){e.printStackTrace();}

Code for First Record:


Try{results.first();
name = results.getString(1);
address = results.getString(2);
System.out.println(name);
num = results.getString(3);
email = results.getString(4);
nameText.setText(name);
addressText.setText(address);
phoneTxt.setText(num);
emailTxt.setText(email);
}
} catch(SQLException e){e.printStackTrace();}

 The first, previous, next, last, absolute, and relative methods all return a true value
if the new row exists and a false value if the new row doesn’t exist or the result
isn’t valid.
 All of the methods in this figure throw an exception of the SQLException type.

How to modify data in a result set


results.moveToInsertRow( );
// updating data
results.updateString( "name", name );
results.updateString( "address", address );
results.updateString( "phone", num );
results.updateString( "email", email );
results.insertRow( );

ClearActionPerformed(evt);
save.setEnabled(false);
cancel.setEnabled(false);

How to update a record


String name="";
String address="";
String email="";
String num="";
try{

name= nameText.getText();
address= addressText.getText();
num= phoneTxt.getText();
email= emailTxt.getText();

// updating data
results.updateString( "name", name );
results.updateString( "address", address );
results.updateString( "phone", num );
results.updateString( "email", email );
results.updateRow( );
JOptionPane.showMessageDialog(this, "Updated");
ClearActionPerformed(evt);
}catch(Exception e){e.printStackTrace();}

How to delete a record

try{
int res= JOptionPane.showConfirmDialog(null,
"Press Yes to Delete", "Press Yes to Delete", JOptionPane.YES_NO_OPTION);
if(res==JOptionPane.YES_OPTION){ClearActionPerformed(evt);
results.deleteRow( );}

}catch(Exception e){e.printStackTrace();}

Extra methods
Code for Clear Button:
private void ClearActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
// int res=JOptionPane.showConfirmDialog(this, " Do you Wanna Clear Data");
// if(res==JOptionPane.YES_OPTION){
nameText.setText("");
addressText.setText("");
phoneTxt.setText("");
emailTxt.setText("");//}

Creating Db using Derby:

 Go to Services Tab in NetBeans


 Right Click on Java Db and Create Database:
Connect to The Database: AddressBook
Now Open The App Schema
Now Create Table contacts
Add columns/fields of Table.

Now go to view data and insert data in the table:


Register Derby Driver :

From location on C drive.

Add derbyClient jar file to the project .


Reporting in java
JasperReport is a popular reporting tool used by the Java programmer. Much like other Java
libraries, JasperReport is an API to facilitate reporting output in a variety of formats, be it, PDF,
XML, HTML, XLS, etc. Further this library is not limited to adding reporting capabilities to web-
based applications only; it can also be used to generate reports from desktop and console
applications as well. In this article we shall see how to go hands on rather than delving into its
architectural details.

1) Obviously, Jasper Library needs to be added to our project and some sort of layout has to be
generated before we are able to start reporting from Java code.

2) Jasper's reporting layout design is nothing but an XML file with the extension
<filename>.jrxml.

3) This JRXML file is to be compiled to create <filename>.jasper. JRXML file can be compiled
on the fly, dynamically from our Java code or we can use iReport or JasperStudio to visually
design the JRXML file and then compile to create a Jasper file.

4) Once compiled and <filename>.jasper are created, we are done and can feed data into the
report from the Java code.

Link to download JAsperReport:


http://sourceforge.net/projects/jasperreports/files/jasperreports/
iReport Plugin:
Download Link:
http://plugins.netbeans.org/plugin/4425/ireport

After downloading the plugin, follow the listed steps to install the plugin in NetBeans:

1. Start the NetBeans IDE.


2. Go to Tools | Plugins.
3. Select the Downloaded tab.
4. Press Add Plugins….

5. Select the plugin files. For iReport 5.5.0 the plugins are: iReport-
5.5.0.nbm, jasperreports-components-plugin-5.5.0.nbm, jasperreportsextensions-
plugin-5.5.0.nbm, and jasperserver-plugin-5.5.0.nbm. After opening the plugin files you
will see the following screen:
6. Check the Install checkbox of ireport-designer, and press the Install button at the
bottom of the window. The following screen will appear:

7. Press Next >, and accept the terms of the License Agreement.
8. If the Verify Certificate dialog box appears, click Continue.
9. Press Install, and wait for the installer to complete the installation.

10. After the installation is done, press Finish and close the Plugins dialog. If the IDE
requests for a restart, then do it. Now the IDE is ready for creating reports.
Creating reports
We have already learnt about creating various types of reports, such as reports without
parameters, reports with parameters, reports with variables, subreports, crosstab reports,
reports with charts and images, and so on. We have also attained knowledge associated
with these types of reports. Now, we will learn quickly how to create these reports using
NetBeans with the help of the installed iReport plugins.

Creating a NetBeans database


JDBC connection
The first step is to create a database connection, which will be used by the report data
sources. Follow the listed steps:

1. Select the Services tab from the left side of the project window.
2. Select Databases.
3. Right-click on Databases, and press New Connection….

4. In the New Database Connection dialog, set the following under Basic setting, and
check theRemember password checkbox:

Option Value

Driver Name MySQL (Connector/J Driver)

Host localhost
Port 3306

Database inventory

User Name root

Password packt

5. Press OK. Now the connection is created, and you can see this under the Services |
Databasessection, as shown in the following screenshot:
Creating a report data source
The NetBeans database JDBC connection created previously will be used by a report data
source that will be used by the report. Follow the listed steps to create the data source:

1. From the NetBeans toolbar, press the Report Datasources button. You will see the
following dialog box:

2. Press New.
3. Select NetBeans Database JDBC connection, and press Next >.
4. Enter inventory in the Name field, and from the Connection drop-down list,
selectjdbc:mysql://localhost:3306/inventory [root on Default schema].

5. Press Test, and if the connection is successful, press Save and close
the Connections / Datasourcesdialog box.
Creating a simple report
We are going to create a report, which shows the list of products. Just follow the listed steps:

1. Go to File | New File….


2. Select Report from the Categories: section and Report Wizard from the File
Types: section, as shown in the next screenshot:

3. Press Next >. Select the Simple Blue layout and press Next > again.
4. Enter ProductListNB.jrxml as File Name:, and Browse… to the reports folder.

5. Press Next >.


6. Select inventory from the Connections / Data Sources options.
7. Write the following SQL command as the query:
SELECT ProductCode, Name, Description
FROM Product
8. Press Next >. You will see the following screen:

9. Select all the fields, press >>, and then press Next >.
10. Press Next > again without selecting any group.
11. Press Finish. You will see the following output:

12. Click on the Preview button to see the output, as shown in the following screenshot:
13. You can design the report in the Designer section as per your design requirements.
Creating a parameterized report
We are going to create a report in NetBeans that shows the information of a particular user.
Follow the listed steps:

1. Go to File | New File….


2. Go to File | New File….
3. Select Report from the Categories: section and Report Wizard from the File
Types: section.
4. Press Next > and select Simple Blue and press Next > again.
5. Enter param.jrxml as the File Name:.
6. Press Next >.
7. Select address from the Connections / Data Sources drop-down list.
8. Write the following SQL command as the query:

SELECT * FROM Customer


9. Press Next >.
10. Select all the fields, press >>, and then press Next >.>>
11. Press Next > again without selecting any group.
12. Press Finish. You will see the Designer view of the report.
13. From the Report Inspector (see bottom left of the designer),
14. select Parameters. Right-click on it, and click on Add Parameter.
15. A parameter named parameter1 is added to the Parameters list.
Select parameter1, and go to the parameter Properties window (see bottom-right of
the designer).

16. Change the Name to Name(i.e parameter name corresponding to the field name)
17. Change the Parameter Class to java.lang.String
18. Check the Use as a prompt checkbox.
19. Now, click on Report query (beside the Preview button),
20. Replace the query with the following one.(Note P must be in capital)
SELECT * FROM Contacts
WHERE name= $P{Name}
21. Press OK and Preview the report. Input the customerNo, and see the output.
Passing Parameter from JFrame to report
First we need to import the following file to our project.

To call the report you must have to include the following jars in classpath-

i.e add these jar file from lib folder of Jasper report project Zip file

1. commons-beanutils-1.9.0.jar
2. commons-collections-3.2.1.jar
3. commons-digester-2.1.jar
4. commons-logging-1.1.1.jar
5. groovy-all-2.0.1.jar
6. iText-2.1.7.jar
7. jasperreports-6.1.0.jar

We are going call report from NetBeans that shows the information of a particular user.
Follow the listed steps:

1. Add a Button and a JTextField on the Jframe

2. Now add the Following Code on The actionPerformed Event


String parameterName = param.getText();
String reportSource = "src/param.jrxml";
// set parameters
Map map = new HashMap();
map.put("Name", parameterName);
JasperReport jasperReport =(JasperReport)
JasperCompileManager.compileReport(reportSource);
JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, map, DBconn);
//here second argument is false so that the report will not close the Jframe with its close
Operation
JasperViewer.viewReport(jasperPrint,false);

.
3. Run the program and provide parameter and Click the generate param button
4. Report for specific user is generated

Generate Report From JFrame without Parameters

1. Add the following code on The generate Button.


private void jButton7ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
try{
String rep="f:\\NetBeansProjects\\ExampleDb\\src\\report1.jrxml";

JasperReport jasperReport =(JasperReport)


JasperCompileManager.compileReport(rep);
JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, null,
DBconn);
//here second argument is false so that the report will not close the Jframe with its
close Operation
JasperViewer.viewReport(jasperPrint,false);
}catch(Exception e){}
}

2. Run the program and generate report without parameter by Clicking the generate
button

You might also like