Sunteți pe pagina 1din 19

CHAPTER-6

DATABASE CONNECTIVITY

The most popular programming interface for accessing


relational database is ODBC (Open Database
Connectivity) But ODBC is Microsoft API which
cannot be directly used from within Java. If you want to
connect to a relational database (e.g. MYSQL or
Oracle’s) from within Java we can do it using
JDBC(Java Database Connectivity)API of java.
We may even use JDBC-ODBC connector that is JDBC
layer over ODBC but JDBC is a better choice for
accessing database like MYSQL.

SUN prepare and maintains the JDBC specification.


Since JDBC is just a specification (Suggestion for
writing and using JDBC drivers), third party vendors
develop JDBC drivers which follows this specification.
JDBC developers then use these drivers to access data
source.

JDBC API
In general, JDBC do three things:-
● Establishes a connection with a database.
● Sends SQL statements.
● Process the result.
The Driver Manager class is the management layer of
JDBC, working between the user and the drivers. It
keeps track of the drivers that are available and handles
establishing a connection between a database and the
appropriate driver.

Note:-The JDBC API is available in the java.sql and


javax.sql packages.
1.VIEWING THE RECORD USING JTABLE
STEPS FOR CREATING DATABASE CONNECTIVITY APPLICATION:-

There are mainly six steps that must be followed in order to create a database
connectivity application

Step-1: Import the package required to Database Programming.


Step-2: Register the Driver.
Step-3: Open a Connection.
Step-4: Execute a Query.
Step-5:Extract Data from Result set
Step-6:Clean up the Environment
import java.sql.*;
Step-1

DefaultTableModel
model=(DefaultTableModel)jTable1.getModel();
try
{
Class.forName("java.sql.Driver");
Connection Step-2
con=DriverManager.getConnection("jdbc:mysql://
localhost/connectivity","root",""); Step-3
Statement stmt=con.createStatement();
String query="select * from dept;"; Step-4
ResultSet rs=stmt.executeQuery(query);

while(rs.next())
{
String dno=rs.getString("deptno");
String dname=rs.getString("dname");
String location=rs.getString("location");
model.addRow(new Step-5
Object[]{dno,dname,location});
}
rs.close(); Step-6
stmt.close();
con.close();

}
catch(Exception e)
{
JOptionPane.showMessageDialog(null,
e.getMessage());
}

Classes used for Database Connectivity:-


There are four main classes in the JDBC API hierarchy
that are generally used for database connectivity.
These are:-
1. DriverManager Class:- The JDBC
DriverManager class loads the JDBC driver needed to
access a particular data source, locates and logs on to
the database and returns a Connection object.
2. Connection Class:- The JDBC Connection class
manage the communications between a Java client
application and a specific database including passing
SQL statements to the DBMS and managing
transaction.
3. Statement Class:- The JDBC Statement class
contains SQL strings that are submitted to the DBMS.
An SQL Select statement return a ResultSet object that
contains the data retrieved as the result of SQL
statement.
4. ResultSet Class:- The JDBC ResultSet class
provides predefined methods to access, analyze, and
convert data values returned by an executed SQL
Select statement.
The required JDBC driver must be registered with the
JDBC Driver Manager before a connection between
the java application and the JDBC data source can be
made. We do it by using Class.forName() method.

Explanation of steps for creating Database


Connectivity Applications:-

Step-1:- Import the packages required for Database


Programming. This steps consists of two sub-steps:-
(a) Firstly we will write the following import
statements at the top of our application’s source code:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import java.sql.ResultSet;

In place of importing separate classes from java.sql


package, we can import the entire package also by
writing one import command as follows:-
import java.sql.*;
(b) Secondly, we need to add the MYSQL JDBC
Connector in our NetBeans project.

Step-2:- Register the JDBC Driver


In this step, we need to initialise a driver so we can
open a communication channel with the database from
within the Java application. For achieving this, we
need to first register the JDBC driver with the
DriverManager. The java.lang package’s one class
namely Class offers a method called forName() that
registers the driver with the DriverManager.
Following is the syntax to achieve this:-
Class.forName(“<driver’s name>”);

Step 3:- Open a Connection

A Connection(represent through Connection


Object) is the session between the application
program and the database. To do anything with the
database one must have a connection object.

This steps requires using the


DriverManager.getConnection()method to create a
Connection object, which represents a physical
connection with the database. The Connection object
allows us to establish a physical connection to the data
source.
The getConnection()method requires the following
arguments:-
URL :-
jdbc:mysql://localhost[:<portnumber>]/<database_na
me>
Here port number 3306 is default and may be used
optionally.
UID:- It is the user name or by Default root is taken.
Password:- The password for the user.(Blank string if
no password is set for accessing MySql database)

Step 4:- Execute a Query


The Statement object is the object used for
executing one static SQL statement on the
associated database-table and returning the results
it produces.

In this step, we need to first create an object of type


Statement or Prepared Statement for building and
submitting an SQL statement to the database using
createStatement() method of Connection type object.
Statement stmt=con.createStatement();
Next we need to execute the SQL statement using
executeQuery() method which return a ResultSet(an
object of ResultSet type) that contains the resultant
dataset of the executed query. So, we must store the
returned value of executeQuery()into a ResultSet
object.

A result set(represented by a ResultSet object) refers to


a logical set of records that are fetched from the
database by executing a query and made available to
the application-program.

ResultSet Cursor:- When a ResultSet object is first


created, the cursor is positioned before the first
row. To move the cursor to first row, we can either
write rs.next() or rs.first().rs.next() forwards the
cursor by one row-since initially the cursor is
before the first record.

Step-5 Extract Data from Result set


This step is required in case we are fetching data from
the database i.e. , in case of Select query we can use
the appropriate ResultSet method.
e.g. Datatype variablename=rs.get<type>;

Step-6 Clean up the Environment


After all the processing, final step is to clean the
environment. In this step we should explicitly close all
database resources using close() method.
rs.close();
stmt.close();
con.close();

Note:- we can use the following code for refreshing


the rows at run time.
int rows=model.getRowCount();
if(rows>0)
{
for(int i=0;i<rows;i++)
{
model.removeRow(0);
}
}

2.Searching the records on the basis of user


Criteria
using combo Box:-
jButton1.doClick();
DefaultTableModel
model=(DefaultTableModel)jTable1.getModel();
try
{
Class.forName("java.sql.Driver");
Connection
con=DriverManager.getConnection("jdbc:mysql://loca
lhost:3306/connectivity","root","");
Statement stmt=con.createStatement();
String
sfield=(String)jComboBox1.getSelectedItem();
String
op=(String)jComboBox2.getSelectedItem();
String crit=jTextField1.getText();
String q1="select deptno,dname,location from
dept where "+(sfield)+" "+(op)+" "+(crit)+";";
JOptionPane.showMessageDialog(this,q1);
ResultSet rs=stmt.executeQuery(q1);
while(rs.next())
{
model.addRow(new
Object[]{rs.getString(1),rs.getString(2),rs.getString(3)
});
}
rs.close();
stmt.close();
con.close();
}
catch(Exception e)
{
JOptionPane.showMessageDialog(this,
e.getMessage()); }

3.Deleting a record on the basis of condition using


listbox control:-
Coding of the application:-
ActionPerformed event of Add Data Button:-
DefaultListModel
d1=(DefaultListModel)jList2.getModel();
try
{
Class.forName("java.sql.Driver");
Connection
con=DriverManager.getConnection("jdbc:mysql://loca
lhost/connectivity","root","");
Statement stmt=con.createStatement();
String sql="Select deptno from dept;";
ResultSet rs=stmt.executeQuery(sql);
while(rs.next())
{
d1.addElement(rs.getString("deptno"));
}
}
catch(Exception e)
{
JOptionPane.showMessageDialog(this,
e.getMessage());
}
MouseClicked event of list-box control:-
String SQL = "SELECT * FROM dept;";
try {
Class.forName("java.sql.Driver");
Connection con = (Connection)

DriverManager.getConnection("jdbc:mysql://localhost
:3306/connectivity","root","");
Statement stmt=con.createStatement();
String dno = (String)
jList2.getSelectedValue();
String SQL1 = "SELECT * FROM dept where
deptno = '"+(dno)+"';";
// Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(SQL1);

while (rs.next()) {
jTextField1.setText(rs.getString("deptno"));
jTextField2.setText(rs.getString("dname"));

jTextField3.setText(rs.getString("location"));

}
}
catch (Exception e) {

JOptionPane.showMessageDialog(this,e.getMessage()
);

ActionPerformed event of Delete-Record Button:-

DefaultListModel
d1=(DefaultListModel)jList2.getModel();
String deptno=(String)jList2.getSelectedValue();
try
{
Class.forName("java.sql.Driver");
Connection
con=DriverManager.getConnection("jdbc:mysql://loca
lhost/connectivity","root","");
Statement stmt=con.createStatement();
String q="delete from dept where
deptno="+deptno;
jTextField1.setText("");
jTextField2.setText("");
jTextField3.setText("");
stmt.executeUpdate(q);
JOptionPane.showMessageDialog(null,"record
deleted successfully");
d1.removeAllElements();
String q1="Select deptno from dept;";
ResultSet rs=stmt.executeQuery(q1);
while(rs.next())
{
d1.addElement(rs.getString(1));
}
}
catch(Exception e)
{
JOptionPane.showMessageDialog(this,
e.getMessage());
}
ActionPerformed event of Delete-ALLRecoed
Button:-
DefaultListModel dmodel =
(DefaultListModel)jList1.getModel();
dmodel.removeAllElements();
jTextField1.setText("");
jTextField2.setText("");
jTextField3.setText("");

4. Inserting the record in the database table:-


try
{
Class.forName("java.sql.Driver");
Connection
con=DriverManager.getConnection("jdbc:mysql://loca
lhost/connectivity","root","");
Statement stmt=con.createStatement();
int
dno=Integer.parseInt(jTextField1.getText());
String dname=jTextField2.getText();
String location=jTextField3.getText();
String q1="insert into teacher
values('"+(dno)+"','"+(dname)+"','"+(location)+"');";
stmt.executeUpdate(q1);
JOptionPane.showMessageDialog(this,"Record
inserted");
}
catch(Exception e)
{
JOptionPane.showMessageDialog(this,
e.getMessage());

S-ar putea să vă placă și