What
is JDBC ad Why do we need it?
·
It is an API Java DataBase Connectivity
·
Connect to the DataBase.
·
Retrieve Data from DataBase
·
Insert data into DataBase.
Steps for JDBC
Program
o
Register a Driver
o
Connect to the DataBase
o
SQL Statements
o
Executing SQL Statements
o
Retrieving Results
o
Closing Connection
How
to Register a Driver?
Option
1:
You
can register a driver with the help of registerDriver() method.
For
example,
DriverManger.registerDriver(
new sun.jdbc.odbc.jdbcodbcDriver());
Option
2:
You
can register a driver with the help of forName() method.
For
example,
Class.forName(sun.jdbc.odbc.jdbcodbcDriver);
How To Connect To DataBase?
1.You should pass
the URL of the DataBase.
2.You should give
DataBase UserName.
3. You should give
DataBase Password.
Please see the below code.
DriverManager.getConection(“jdbc:odbc:oradsn”, “scott”,
“sa”);
How To Prepare SQL Statements?
Here you can use two ways.
1.Statement
2.Prepared Statement
For executing query we can use both, But the difference
is Perpared Statement is Fast and It is Pre Compile.
Please look the below code.
Statement stmt = con.createStatement();
Now we have to execute the query with the help of
executeQuery() method.
ResultSet rs = stmt.executeQuery(“select * from vendor”);
Now the query will be executed and result will be
stored into ResultSet.
ResultSet have some methods. You can use this for retrieving
datas.
The methods are,
String getString()
int getInt()
float getFloat()
etc.,.
How to use these methods, can see later in example.
Example Program for JDBC Connection:
import java.sql.*;
class TestJdbc {
public
static void main(String args[]) {
//Driver
Register
DriverManger.registerDriver( new
sun.jdbc.odbc.jdbcodbcDriver());
//Connection with database
Connection
con = DriverManager.getConnection(“jdbc:oracle:thin:@localhost:1521: xe”,
“test” , “sa”);
//
for creating sql statement
Statemet
stmt = con.createStatement();
//Executing
statement
ResultSet
rs = stmt.executeQuery(“Select * form vendor”);
//
Retreiving results
While(rs.next())
{
System.out.pritln(“The
vendor ID is ” + rs.getInt(1));
System.out.pritln(“Vendor
Name ” + rs.getString());
System.out.pritln(“Vendor
Fund Percent” + rs.getFloat());
}
con.close();
}
}