Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 18

Java JDBC

Java JDBC is a java API to connect and execute query with the database. JDBC API uses
jdbc drivers to connect with the database.

Why use JDBC

1. JDBC stands for Java Data Base Connectivity Where as ODBC stands for Open Data
Base Connectivity.

2. Before JDBC, ODBC API was the database API to connect and execute query with
the database. But, ODBC API uses ODBC driver which is written in C language (i.e.
platform dependent and unsecured). That is why Java has defined its own API (JDBC
API) that uses JDBC drivers (written in Java language).

3. JDBC drivers are written in java and JDBC code is automatically installable, secure,
and portable on all platforms. ODBC requires manual installation of the ODBC driver
manager and driver on all client machines.

What is API

API (Application programming interface) is a document that contains description of all the
features of a product or software. It represents classes and interfaces that software programs
can follow to communicate with each other. An API can be created for applications, libraries,
operating systems, etc

JDBC Driver

JDBC Driver is a software component that enables java application to interact with the
database. OR
The JDBC driver is the mediator between the Java application and the database.
There are 4 types of JDBC drivers:
1. JDBC-ODBC bridge driver
2. Native-API driver (partially java driver)
3. Network Protocol driver (fully java driver)
4. Thin driver (fully java driver)

1) JDBC-ODBC bridge driver

The JDBC-ODBC bridge driver uses ODBC driver to connect to the database. The JDBC-
ODBC bridge driver converts JDBC method calls into the ODBC function calls. This is
now discouraged because of thin driver.

Advantages:
o easy to use.
o can be easily connected to any database.

Disadvantages:

o Performance degraded because JDBC method call is converted into the ODBC
function calls.
o The ODBC driver needs to be installed on the client machine.
2) Native-API driver

The Native API driver uses the client-side libraries of the database. The driver converts
JDBC method calls into native calls of the database API. It is not written entirely in java.

Advantage:

o performance upgraded than JDBC-ODBC bridge driver.

Disadvantage:

o The Native driver needs to be installed on the each client machine.


o The Vendor client library needs to be installed on client machine.
3) Network Protocol driver

The Network Protocol driver uses middleware (application server) that converts JDBC calls
directly or indirectly into the vendor-specific database protocol. It is fully written in java.

Advantage:

o No client side library is required because of application server that can perform many
tasks like auditing, load balancing, logging etc.

Disadvantages:

o Network support is required on client machine.


o Requires database-specific coding to be done in the middle tier.
o Maintenance of Network Protocol driver becomes costly because it requires database-
specific coding to be done in the middle tier.
4) Thin driver

The thin driver converts JDBC calls directly into the vendor-specific database protocol.
That is why it is known as thin driver. It is fully written in Java language.

Advantage:

o Better performance than all other drivers.


o No software is required at client side or server side.

Disadvantage:

o Drivers depends on the Database.


The important steps in the jdbc
1. Loading the driver class into the memory.

2. Establishing the connection from the database.

3. Executing the SQL statement.

4. Closing the Connection which is very important

Steps for Establishing a Database Connection

1.Establishing a Connection

 Loading Drivers or Loading DriverManager

Note : Syntax of loading the Class file:


Class.forName(“DriverManagerClass”);

The following are different Loading DriverManager :

Jdbc-Odbc Bridge : sun.jdbc.odbc.JdbcOdbcDriver


Oracle : oracle.jdbc.driver.OracleDriver
DB2 : COM.ibm.db2.jdbc.app.DB2Driver
Pointbase : com.pointbase.jdbc.jdbcUniversalDriver
Sybase : com.sybase.jdbc2.jdbc.SybDrive
SQL-Server : weblogic.jdbc.mssqlserver4.Driver
MsAccess : Jdbc:Odbc:rsdn

NOTE:Example for Jdbc-Odbc bridge driver:

Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);

2.Making the Connection

Connection con = DriverManager.getConnection(“url”, “myLogin", "myPassword");

NOTE:Example

Connection c =DriverManager.getConnection("jdbc:odbc:mydsn","bvpr","cs");
Connecting through DSN :

Connection con =

DriverManager.getConnection(“jdbc:odbc:dsnname”);

Connection con =

DriverManager.getConnection(“jdbc:odbc:dsnname”, “username”, “password”);

Connection con =

DriverManager.getConnection("jdbc:oracle:oci“, “username”, “password”);

Connection con =

DriverManager.getConnection("jdbc:oracle:thin:@ipaddress:port:hoststring”, “username”,
“password”)

Closing the Database Connection

 To close the database call the Connection close() method.


 This method immediately releases the database and JDBC resources associated
with the given Connection.

JDBC Statements

A Statement object is used to send the SQL statement to the database.


The Statement object must be created by using the open Connection object.

Types of Statements:

1. Statement createStatement()
2. PreparedStatement prepareStatement(String sql)

3. CallableStatement prepareCall(String sql)


1. Create Statement: It is used to execute SQL statements.
The syntax for creating the statement.

 Methods for execute a statement:


There are 3 important Statement methods

1. stmt.executeUpdate()
2. stmt.executeQuery()
3. stmt.execute()

Statement Methods:Decription

1. ResultSet executeQuery(String SQLStatement)

Execute a SQL statement that returns a single ResultSet.

2. Int executeUpdate(String SQLStatement)

Execute a SQL INSERT, UPDATE or DELETE statement.

Returns the number of rows changed.

3. boolean execute(String)

Execute a SQL statement that may return multiple results.

2. Prepared Statement: Used to prepare statements with place holders (?) to set the
values at run time.

PreparedStatement: - is used when an application plans to reuse a statement multiple times. The
application prepares the SQL it plans to use. Once prepared, the application can specify values for
parameters in the prepared SQL statement.

PreparedStatement ps = con.prepareStatement(“Query with Place Holders”);

Example:

PreparedStatement ps = con.prepareStatement(“select * from emp where empno=?”);


PreparedStatement ps = con.prepareStatement(“insert into emp(empno, ename, sal, deptno)
values(?,?,?,?)”);

Set values for place holders

ps.setInt(int, int);

ps.setString(int, String);

……..

ps.setXXX(int, XXX);

Executing the PreparedStatement

ResultSet rs=ps.executeQuery();

int n=ps.executeUpdate();

boolean b=ps.execute();

3. Callable Statement: Used to execute functions or procedures available in data base.

A CallableStatement is used to call stored procedures that return values. It also has methods for
retrieving the return values of the stored procedure.

• CallableStatement cs = con.prepareCall(“{call fun/prod(?,?)}”);


con.prepareCall("{?=call fun/prod(?)}");

Example:

• CallableStatement cs = con.prepareCall(“{call emp.insert(?,?,?)}”);

JDBC Exceptions:

1.

catch (ClassNotFoundException e)
{
e.printStackTrace();
}
2.
catch (SQLException e)
{
e.printStackTrace();
}
Note::Querying the Database

 The ResultSet object contains the rows retrieved from the database query.
 To access each row use ResultSets’s next() method.
 This method moves a database cursor sequentially through the rows retrieved from
the query

ResultSet

1. A ResultSet provides access to a table of data generated by executing a Statement.


2. Only one ResultSet per Statement can be open at once.
3. The table rows are retrieved in sequence.
4. A ResultSet maintains a cursor pointing to its current row of data.
5. The 'next' method moves the cursor to the next row.
6. Is an Object which stores data of the select statement result in records and fields form.
7. By default it is Forward Only and Read Only.
8. Result Set Navigation and updating is possible from new API version 1.2 onwards.
9. The ResultSet object contains the rows retrieved from the database query.
10. This method moves a database cursor sequentially through the rows retrieved from the
query.

ResultSet Methods

1. boolean next()
a. activates the next row
b. the first call to next() activates the first row
c. returns false if there are no more rows
2. void close()
a. disposes of the ResultSet
b. allows you to re-use the Statement that created it
c. automatically called by most Statement methods

3. Type getType(int columnIndex)


a. returns the given field as the given type
b. fields indexed starting at 1 (not 0)
4. Type getType(String columnName)
a. same, but uses name of field
b. less efficient

5. int findColumn(String columnName)


a. looks up column index given column name
6. String getString(int columnIndex)
7. boolean getBoolean(int columnIndex)
8. byte getByte(int columnIndex)
9. short getShort(int columnIndex)
10. int getInt(int columnIndex)
11. long getLong(int columnIndex)
12. float getFloat(int columnIndex)
13. double getDouble(int columnIndex)
14. Date getDate(int columnIndex)
15. Time getTime(int columnIndex)
16. Timestamp getTimestamp(int columnIndex
17. String getString(String columnName)
18. boolean getBoolean(String columnName)
19. byte getByte(String columnName)
20. short getShort(String columnName)
21. int getInt(String columnName)
22. long getLong(String columnName)
23. float getFloat(String columnName)
24. double getDouble(String columnName)
25. Date getDate(String columnName)
26. Time getTime(String columnName)
27. Timestamp getTimestamp(String columnName)

Syntax::Retrieving Values from ResultSet


 ResultSet rs = Stms.executeQuery(“SELECT name FROM mytable where id = 1”) ;
 Example for Methods will be used in ResultSet
 next()
 getString()
 getInt()

String query = "SELECT id, name FROM mytable";

ResultSet rs = stmt.executeQuery(query);

while (rs.next())

String s = rs.getInt("id");

float n = rs.getString("name");

System.out.println(s + " " + n); }

Metadata:It is the data about data.


1. Connection:
DatabaseMetaData getMetaData():provides entire information for the database. (Or
)How many number of different tables or views are existing in database.

2. ResultSet: provides particular or limited information in specific table..


ResultSetMetaData getMetaData()

ResultSetMetaData

The following information is provide the ResultSetMetaData:

1. What's the number of columns in the ResultSet?


2. What's a column's name?
3. What's a column's SQL type?
4. What's the column's normal max width in chars?
5. What's the suggested column title for use in printouts and displays?
6. What's a column's number of decimal digits?
7. Does a column's case matter?
8. Is the column a cash value?
9. Will a write on the column definitely succeed?
10. Can you put a NULL in this column?
11. Is a column definitely not writable?
12. Can the column be used in a where clause?
13. Is the column a signed number?
14. Is it possible for a write on the column to succeed?
15. and so on...

ResultSetMetaData: It is Data about Data of ResultSet like field names, no. of Columns etc.

Methods:

ResultSetMetaData rsmd = rs.getMetaData();

int count = rsmd.getColumnCount();

Strting fname = rsmd.getColumnName(int index);

int dn = rsmd.getColumnType(int index);

String dn = rsmd.getColumnTypeName(int index);

String alias = rsmd.getColumnLabel(int index);

DatabaseMetaData

The following information is provide the DatabaseMetaData

1. What tables are available?


2. What's our user name as known to the database?
3. Is the database in read-only mode?
4. If table correlation names are supported, are they restricted to be different from the names
of the tables?
DATABASE conn APPLICATION

import java.sql.*;
import java.io.*;
class dbscon
{
public static void main(String s1[])
{
ResultSet r=null;

try

{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection c=DriverManager.getConnection("jdbc:odbc:mydn","username","pwd");

Statement st=c.createStatement();

r=st.executeQuery("select * from emp");

while(r.next())

String cc=r.getString("empno");

cc= cc+" : "+r.getString("ename");

System.out.println(cc);

catch(Exception e)

{
System.out.println(e);
}

}
}
// DATABASE conn Update

import java.sql.*;

import java.io.*;

class dbconupdt

public static void main(String s1[])

ResultSet r=null;

try

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

Connection c=DriverManager.getConnection("jdbc:odbc:mydn", “uname”,”pwd”);

Statement st=c.createStatement();

int n=st.executeUpdate("update csa set name='BBB' where stdno=10");

System.out.println(n);

catch(Exception e)

System.out.println(e);

}
//

DATABASE conn INSERT

import java.sql.*;

import java.io.*;

class dbconins

public static void main(String s1[])

ResultSet r=null;

try

BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

Connection c=DriverManager.getConnection("jdbc:odbc:mydn","uname",”pwd”);

Statement st=c.createStatement();

System.out.print("Enter idno : ");

String id=br.readLine();

System.out.print("Enter NAME : ");

String nm=br.readLine();

String qr="insert into csa values("+id+",'"+nm+"')";

int n=st.executeUpdate(qr);

System.out.println(n);

catch(Exception e)

{
System.out.println(e);

// DATABASE conn DELETE

import java.sql.*;

import java.io.*;

class dbcondel

public static void main(String s1[])

ResultSet r=null;

try

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

Connection c=DriverManager.getConnection("jdbc:odbc:mydn","username","pwd"");

Statement st=c.createStatement();

int n=st.executeUpdate("delete from csa where stdno=20");

System.out.println(n);

catch(Exception e)

System.out.println(e);}

}
}

// DATABASE conn RESULSET METADATA

import java.sql.*;

import java.io.*;

class metdt

public static void main(String s1[])

ResultSet r=null;

try

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

Connection c=DriverManager.getConnection("jdbc:odbc:mydn","username","pwd");

Statement st=c.createStatement();

r=st.executeQuery("select * from emp");

ResultSetMetaData mt=r.getMetaData();

int cl=mt.getColumnCount();

System.out.println("no of COLS : "+cl);

System.out.println("CLOS MNAMES ARE :: ");

for(int i=1;i<=(cl-2);i++)

System.out.print(mt.getColumnName(i)+" ");

System.out.println();

while(r.next())

for(int i=1;i<=(cl-2);i++)
{

System.out.print(r.getString(i)+" ");}

System.out.println();

r.close();st.close();c.close();

catch(Exception e)

System.out.println(e);

You might also like