Sunteți pe pagina 1din 19

connect to the database in java

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 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 sub protocol. The first
driver that recognizes a certain subprotocol under JDBC will be
used to establish a database Connection.
Driver: This interface handles the communications with the
database server. You will interact directly with Driver objects very
rarely. Instead, you use DriverManager objects, which manages
objects of this type. It also abstracts the details associated with
working with Driver objects.
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 an SQL query using
Statement objects. It acts as an iterator to allow
you to move through its data.
SQLException: This class handles any errors that
occur in a database application.
There are 5 steps to connect any java
application with the database in java using
JDBC. They are as follows:
Register the driver class
Creating connection
Creating statement
Executing queries
Closing connection
Register the driver class

The forName() method of Class class is used to register


the driver class. This method is used to dynamically
load the driver class.
Syntax of forName() method
public static void forName(String className)throws Cl
assNotFoundException

Example to register the OracleDriver class


Class.forName("oracle.jdbc.driver.OracleDriver");
Create the connection object

The getConnection() method of DriverManager class is used


to establish connection with the database.
Syntax of getConnection() method
1) public static Connection getConnection(String url)throws
SQLException
2) public static Connection getConnection(String url,String
name,String password)
throws SQLException
Example to establish connection with the Oracle database
Connection con=DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe","system","password"
);
Create the Statement object

The createStatement() method of Connection


interface is used to create statement. The
object of statement is responsible to execute
queries with the database.
Syntax of createStatement() method
public Statement createStatement()throws SQ
LException
Example to create the statement object
Statement stmt=con.createStatement();
Execute the query

The executeQuery() method of Statement interface is used


to execute queries to the database. This method returns the
object of ResultSet that can be used to get all the records of
a table.
Syntax of executeQuery() method
public ResultSet executeQuery(String sql)throws SQLExcep
tion
Example to execute query
ResultSet rs=stmt.executeQuery("select * from emp");
while(rs.next()){
System.out.println(rs.getInt(1)+" "+rs.getString(2));
}
Close the connection object

By closing connection object statement and


ResultSet will be closed automatically. The
close() method of Connection interface is used
to close the connection.
Syntax of close() method
public void close()throws SQLException
Example to close connection
con.close();
DBC example with access:

To connect java application to access database we must have at least


one database created in access.
Steps to create a database in MS-Access:
(1) Open Microsoft Office Access.
(2) Click on Blank Database.
(3) Type an appropriate name of database in File Name: box for
example, HOD_DATA and click on Create Button.
(4) Create appropriate field name in table and value as per the field.
5) Right click on Table1 and select Save. Type the name of Table for
example, DATA and click on OK button.
(6) Close the Table by right clicking on DATA and select Close. and
Exit from Database
(7) Move this database to the appropriate drive where you want.
String which we are writing in
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver") to load the
driver.
String which we are writing in Connection con =
DriverManager.getConnection("jdbc:odbc:HOD_DATA") to create
connection with particular database.
Here HOD_DATA is our DSN (Data Source Name).
Steps for creating DSN for access.
(1) Go to Control Panel.
(2) Click on Administrative Tools(Window XP) for (Window 7)
System and Security then Administrative Tools.
(3) Click on Data Sources (ODBC).
(4) Select MS Access Database and Click on Add button
(5) Select Microsoft Access Driver
(*.mdb,*.accdb) and Click on Finish button.
6) Type Data Source Name, for example HOD_DATA then click on Select
button in the Database frame.
(7) Select particular database which we saved on particular drive and created
at beginning of this page (HOd_DATA). and click on OK button.
Click on OK button and Check out the
textarea of Data Sources Administrator. Now
it contains a new DSN as a HOD_DATA.


(9) Click on OK button and close the Administrative Tools (Control
Panel).
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;

public class Prepare_Demo


{
public static void main(String[] args)
{
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con=DriverManager.getConnection("jdbc:odbc:DATA");
PreparedStatement ps = con.prepareStatement("insert into PA
(ID,Name,CITY,AGE)values(?,?,?,?)");
ps.setInt(1,200);
ps.setString(2, "hello");
ps.setInt(4,101);
ps.setString(3, "brd");

ps.executeUpdate();
System.out.println("inserted");
con.close();
}
catch (Exception e)
{
System.out.println(e);
}
}
}

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