[go: up one dir, main page]

0% found this document useful (0 votes)
2 views12 pages

Chapter 3 - GUI & JDBC

Chapter Three introduces Graphical User Interface (GUI) programming in Java using Swing components and the NetBeans IDE, focusing on creating a simple application that accepts input from text fields. It also covers Java Database Connectivity (JDBC), explaining its architecture, components, and different types of JDBC drivers, along with how to establish and manage database connections. The chapter emphasizes the importance of data validation and provides code examples for implementing GUI elements and JDBC functionalities.

Uploaded by

fikadu.meu.edu
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)
2 views12 pages

Chapter 3 - GUI & JDBC

Chapter Three introduces Graphical User Interface (GUI) programming in Java using Swing components and the NetBeans IDE, focusing on creating a simple application that accepts input from text fields. It also covers Java Database Connectivity (JDBC), explaining its architecture, components, and different types of JDBC drivers, along with how to establish and manage database connections. The chapter emphasizes the importance of data validation and provides code examples for implementing GUI elements and JDBC functionalities.

Uploaded by

fikadu.meu.edu
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/ 12

Chapter Three

Graphical User Interface and Java Database


connectivity
Creating Graphical User Interface (GUI) using NetBeans IDE
This chapter provides an introduction to Graphical User Interface (GUI) programming in java
with Swing components (Textfield, buttons, Labels, check box, etc) using NetBeans IDE. A user
interface provides a means to exchange information between a user and a program, in terms of
inputs and outputs. In other words, a user interface defines the way the interaction between the
user and a program takes place. Typing text using a keyboard, selecting a menu item using a
mouse, or clicking a button can provide input to a program. The NetBeans IDE is a free, open-
source, cross-platform integrated development environment with built-in support for Java
programming language.

The goal of this lesson is to introduce the Swing API (Application program Interface) by
designing a simple application that accept values from one textfield and display in second
textfield.

Its GUI will be basic, focusing on only a subset of the available Swing components. We will use
the NetBeans IDE GUI builder, which makes user interface creation a simple matter of drag and
drop. Its automatic code generation feature simplifies the GUI development process, letting you
focus on the application logic instead the underlying infrastructure.

Because this lesson is a step-by-step checklist of specific actions to take, we recommend that you
run the NetBeans IDE and perform each step as you read along. This will be the quickest and
easiest way to begin programming with Swing.

Add Jframeform in your project and drag and drop four textfields, four labels and two buttons.
Let the name of four textfields are txt1, txt2, txt3 and txt4. Let also the caption of the labels are
String Input , Number Input ,Value 1 and Value 2. Let also the name of buttons are btndisplay
and btnclear. Make the caption of the two buttons as Display and Clear as shown below.

1
To give caption/label right click on the button or label or text field and select Edit Text.

To give name right click on textfield or button or label and select Change Variable Name.

Data validations for txt1 and txt2 textfield

Let txt1 must accept only letters and txt2 accept only numbers (0-9). Use the following codes to
do these validations.

//import javax.swing.JOptionPane; at the top of the class

//Letter validation,Right click on txt1,then point to Events then point to Key finally select KeyPessed

private void txt1KeyPressed(java.awt.event.KeyEvent evt) {

if( (evt.getKeyChar() >= 'a' && evt.getKeyChar() <= 'z')||(evt.getKeyChar() >= 'A' && evt.getKeyChar() <=
'Z'))

txt1.setEditable(true);
else {
txt1.setEditable(false);
JOptionPane.showMessageDialog(null," please enter only letter");
txt1.setEditable(true);
}
}
//Number validation
private void txt2KeyPressed(java.awt.event.KeyEvent evt) {
if (evt.getKeyChar() >= '0' && evt.getKeyChar() <= '9')
txt2.setEditable(true);

else {

2
txt2.setEditable(false);
JOptionPane.showMessageDialog(null," please enter only numeric digits(0-9)");
txt2.setEditable(true);
}
}

//Code for btndisplay button


// Right click on btndisplay and point to Events then point to Action and then Actionperformed
private void btndisplayActionPerformed(java.awt.event.ActionEvent evt)
{
String s1=txt1.getText();
txt3.setText(s1);
String s2=txt2.getText();
txt4.setText(s2);
}
private void btnclearActionPerformed(java.awt.event.ActionEvent evt)
{
txt1.setText(“ ”);
txt2.setText(“ “);
txt3.setText(“ “);
txt4.setText(“ “);
}

Java Database Connectivity (JDBC)

What is JDBC?
JDBC stands for Java Database Connectivity, which is a standard Java API (Application
Program Interface) for database-independent connectivity between the Java programming
language and a wide range of databases.

The JDBC library includes APIs for each of the tasks commonly associated with database usage:

 Making a connection to a database


 Creating SQL or MySQL statements
 Executing that SQL or MySQL queries in the database
 Viewing & Modifying the resulting records

3
Fundamentally, JDBC is a specification that provides a complete set of interfaces that allows for
portable access to an underlying database. Java can be used to write different types of
executables, such as:

 Java Applications
 Java Applets
 Java Servlets
 Java ServerPages (JSPs)

All of these different executables are able to use a JDBC driver to access a database and take
advantage of the stored data.

JDBC provides the same capabilities as ODBC, allowing Java programs to contain database-
independent code.

JDBC Architecture:
The JDBC API supports both two-tier and three-tier processing models for database access but in
general JDBC Architecture consists of two layers:

 JDBC API: This provides the application-to-JDBC Manager connection.


 JDBC Driver API: This supports the JDBC Manager-to-Driver Connection.

The JDBC API uses a driver manager and database-specific drivers to provide transparent
connectivity to heterogeneous databases.

The JDBC driver manager ensures that the correct driver is used to access each data source. The
driver manager is capable of supporting multiple concurrent drivers connected to multiple
heterogeneous databases.

Following is the architectural diagram, which shows the location of the driver manager with
respect to the JDBC drivers and the Java application:

4
Common JDBC Components:
The JDBC API provides the following interfaces and classes:

 DriverManager: This class manages a list of database drivers. Matches connection


requests from the java application with the proper database driver using communication
subprotocol.
 Driver: This interface handles the communications with the database server.
 Connection: This interface with all methods for contacting a database. The connection
object represents communication context, i.e., all communication with database is
through connection object only.
 Statement: You use objects created from this interface to submit the SQL statements to
the database. Some derived interfaces accept parameters in addition to executing stored
procedures.
 ResultSet: These objects hold data retrieved from a database after you execute SQL
query using Statement objects. It acts as temporary table that allow you to move through
its data.
 SQLException: This class handles any errors that occur in a database application.

5
What is JDBC Driver?
JDBC drivers implement the defined interfaces in the JDBC API for interacting with your
database server.

For example, using JDBC drivers enable you to open database connections and to interact with it
by sending SQL or database commands then receiving results with Java.

The Java.sql package that ships with JDK contains various classes with their behaviors defined
and their actual implementations are done in third-party drivers. Third party vendors implement
the java.sql.Driver interface in their database driver.

JDBC Drivers Types:


JDBC driver implementations vary because of the wide variety of operating systems and
hardware platforms in which Java operates. Sun has divided the implementation types into four
categories, Types 1, 2, 3, and 4, which are explained below:

Type 1: JDBC-ODBC Bridge Driver:


In a Type 1 driver, a JDBC bridge is used to access ODBC drivers installed on each client
machine. Using ODBC requires configuring on your system a Data Source Name (DSN) that
represents the target database.

When Java first came out, this was a useful driver because most databases only supported ODBC
access but now this type of driver is recommended only for experimental use or when no other
alternative is available.

6
The JDBC-ODBC Bridge that comes with JDK 1.2 is a good example of this kind of driver.

Type 2: JDBC-Native API:


In a Type 2 driver, JDBC API calls are converted into native C/C++ API calls which are unique
to the database. These drivers typically provided by the database vendors and used in the same
manner as the JDBC-ODBC Bridge, the vendor-specific driver must be installed on each client
machine.

If we change the Database we have to change the native API as it is specific to a database and
they are mostly obsolete now but you may realize some speed increase with a Type 2 driver,
because it eliminates ODBC's overhead.

7
The Oracle Call Interface (OCI) driver is an example of a Type 2 driver.

Type 3: JDBC-Net pure Java:


In a Type 3 driver, a three-tier approach is used to accessing databases. The JDBC clients use
standard network sockets to communicate with a middleware application server. The socket
information is then translated by the middleware application server into the call format required
by the DBMS, and forwarded to the database server.

8
You can think of the application server as a JDBC "proxy," meaning that it makes calls for the
client application. As a result, you need some knowledge of the application server's configuration
in order to effectively use this driver type.

Your application server might use a Type 1, 2, or 4 driver to communicate with the database,
understanding the nuances will prove helpful.

Type 4: 100% pure Java:


A Type 4 driver is a pure Java-based driver that communicates directly with vendor's database
through socket connection. This is the highest performance driver available for the database and
is usually provided by the vendor itself.

This kind of driver is extremely flexible; you don't need to install special software on the client
or server. Further, these drivers can be downloaded dynamically.

Oracle thin driver and MySQL's Connector/J driver is a Type 4 driver. Because of the
proprietary nature of their network protocols, database vendors usually supply type 4 drivers.

9
JDBC Database Connections

After you've installed the appropriate driver, it's time to establish a database connection using
JDBC.

The programming involved to establish a JDBC connection is fairly simple. Here are these
simple four steps:

 Import JDBC Packages: Add import statements to your Java program to import
required classes in your Java code.
 Register JDBC Driver: This step causes the JVM to load the desired driver
implementation into memory so it can fulfill your JDBC requests.
 Database URL Formulation: This is to create a properly formatted address that points
to the database to which you wish to connect.
 Create Connection Object: Finally, code a call to the DriverManager object's
getConnection( ) method to establish actual database connection.

Import JDBC Packages:


The Import statements tell the Java compiler where to find the classes you reference in your
code and are placed at the very beginning of your source code.

To use the standard JDBC package, which allows you to select, insert, update, and delete data in
SQL tables, add the following imports to your source code:

import java.sql.* ; // for standard JDBC programs


import java.math.* ; // for BigDecimal and BigInteger support

Register JDBC Driver:


You must register your driver in your program before you use it. Registering the driver is the
process by which the Oracle driver's class file is loaded into memory so it can be utilized as an
implementation of the JDBC interfaces.

You need to do this registration only once in your program.

10
You should use the registerDriver() method if you are using a non-JDK compliant JVM, such as
the one provided by Microsoft.

The following example uses registerDriver() to register the Oracle driver:

try {
Driver myDriver = new oracle.jdbc.driver.OracleDriver();
DriverManager.registerDriver( myDriver );
}
catch(ClassNotFoundException ex) {
System.out.println("Error: unable to load driver class!");
System.exit(1);
}

Database URL Formulation:


After you've loaded the driver, you can establish a connection using the
DriverManager.getConnection() method.

getConnection(String url, String user, String password)

Here each form requires a database URL. A database URL is an address that points to your
database.

Formulating a database URL is where most of the problems associated with establishing a
connection occur.

Following table lists down popular JDBC driver names and database URL.

RDBMS JDBC driver name URL format

MySQL com.mysql.jdbc.Driver jdbc:mysql://hostname:port Number/ databaseName

jdbc:oracle:thin:@hostname:port
ORACLE oracle.jdbc.driver.OracleDriver
Number:databaseName

DB2 COM.ibm.db2.jdbc.net.DB2Driver jdbc:db2:hostname:port Number/databaseName

jdbc:sybase:Tds:hostname: port
Sybase com.sybase.jdbc.SybDriver
Number/databaseName

All the highlighted part in URL format is static and you need to change only remaining part as
per your database setup.

11
Create Connection Object:
Using a database URL with a username and password:
DriverManager.getConnection() method used to create a connection object. It requires you to
pass a database URL, a username, and a password.

Assuming you are using Oracle's thin driver, you'll specify a host:port:databaseName value for
the database portion of the URL.

If you have a host at TCP/IP address 127.0.0.1/localhost with a host name of dmu, and your
Oracle listener is configured to listen on port 1521, and your database name is EMP, then
complete database URL would then be:

jdbc:oracle:thin:@dmu:1521:EMP

Now you have to call getConnection() method with appropriate username and password to get a
Connection object as follows:

String URL = "jdbc:oracle:thin:@dmu:1521:EMP";


String USER = "username";
String PASS = "password"
Connection conn = DriverManager.getConnection(URL, USER, PASS);

Closing JDBC connections:


At the end of your JDBC program, it is required explicitly close all the connections to the
database to end each database session. However, if you forget, Java's garbage collector will close
the connection when it cleans up stale/old objects. Relying on garbage collection, especially in
database programming, is very poor programming practice. You should make a habit of always
closing the connection with the close () method associated with connection object.

To ensure that a connection is closed, you could provide a finally block in your code. A finally
block always executes, regardless if an exception occurs or not.
To close above opened connection you should call close() method as follows:
conn.close();

Explicitly closing a connection conserves DBMS resources, which will make your database

12

You might also like