0% found this document useful (0 votes)
112 views49 pages

Class Presentations On Object Oriented Programming by Subhash Chand Agrawal

This document provides an overview of object oriented programming and Java Database Connectivity (JDBC). It discusses the key concepts of OOP like classes, objects, inheritance and polymorphism. It then explains the five steps to connect a Java application to a database using JDBC: 1) register the driver class, 2) create a connection, 3) create a statement, 4) execute queries, and 5) close the connection. Finally, it covers the different statement interfaces in JDBC - Statement, PreparedStatement and CallableStatement and how to use them.

Uploaded by

Eshan Rathore
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
112 views49 pages

Class Presentations On Object Oriented Programming by Subhash Chand Agrawal

This document provides an overview of object oriented programming and Java Database Connectivity (JDBC). It discusses the key concepts of OOP like classes, objects, inheritance and polymorphism. It then explains the five steps to connect a Java application to a database using JDBC: 1) register the driver class, 2) create a connection, 3) create a statement, 4) execute queries, and 5) close the connection. Finally, it covers the different statement interfaces in JDBC - Statement, PreparedStatement and CallableStatement and how to use them.

Uploaded by

Eshan Rathore
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 49

Object Oriented Programming

JDBC
Class Presentations on Object Oriented Programming
by Subhash Chand Agrawal
Software and drivers
 Jdk 1.8
 https://www.oracle.com/in/java/technologies/javase/javas
e-jdk8-downloads.html
 NetBeans
 https://download.netbeans.org/netbeans/8.0/final/bundle
s/netbeans-8.0-windows.exe
 MySQL 5.5
 https://cdn.mysql.com/archives/mysql-5.5/mysql-5.5.41-
winx64.msi
 JDBC driver
 https://static.javatpoint.com/src/jdbc/mysql-connector.jar
Database Concepts
 Database − A database is a collection of tables,
with related data.
 Table − A table is a matrix with data. A table in a
database looks like a simple spreadsheet.
 Column − One column (data element) contains data
of one and the same kind, for example the column
rollno.
 Row − A row (= tuple, entry or record) is a group
of related data, for example the data of one
subscription.
DataTypes
 Numeric Data Type
 INT
 FLOAT(m,d)
 DOUBLE(m,d)
 String Data Types:
 VARCHAR(size)
 Open your MySQL Command Line Client; it should
have appeared with a mysql> prompt.
 Check the already created databases with show
databases command:
 show databases;
MySQL Create Database
 mysql> CREATE DATABASE subhash;

 We can check the created database using the


following query:
 mysql> SHOW DATABASES;
 Finally, we can use the below command to access
the database that enables us to create a table and
other database objects.
 mysql> USE subhash;
MySQL CREATE TABLE
 create table employee
 (
 id int,
 name varchar(20),
 age int,
 salary float(10,4),
 dept varchar(20)
 );

 insert into employee values( 17,'Dinesh',37,1200.555,'cs');


 We need to use the following command to see the
newly created table:
 mysql> SHOW TABLES;

 We can use the following command to see the


information or structure of the newly created table:
 mysql> DESCRIBE employee_table;
Why to Learn JDBC?
 JDBC stands for Java Database Connectivity, which is a
standard Java API 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
mentioned below that are commonly associated with
database usage.
 Making a connection to a database.
 Creating SQL or MySQL statements.
 Executing SQL or MySQL queries in the database.
 Viewing & Modifying the resulting records.
Applications of JDBC
 Java Applications
 Java Applets
 Java Servlets
 Java ServerPages (JSPs)
 Enterprise JavaBeans (EJBs).
JDBC Architecture
Java Database Connectivity with 5
Steps

 There are 5 steps to connect any java application


with the database using JDBC. These steps are as
follows:
 Register the Driver class
 Create connection

 Create statement

 Execute queries

 Close connection
1) 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
ClassNotFoundException
 Example to register the OracleDriver class
 Class.forName("oracle.jdbc.driver.OracleDriver");

 Example to register the MySQL driver class


 Class.forName("com.mysql.jdbc.Driver");
2) 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","pas

sword");
 Connection con=DriverManager.getConnection(

"jdbc:mysql://localhost:3306/subhash","root","root");
Table
 create table employee
 (
 id int,
 name varchar(20),
 age int,
 salary float(10,4),
 dept varchar(20)
 );

 insert into employee values( 17,'nesh',37,1200.555,'cs');


 import java.sql.*;
 public class JavaApplication7 {
 {
 public static void main(String args[]) {
 try
 {
 Class.forName("com.mysql.jdbc.Driver");
 Connection con = DriverManager.getConnection(
 "jdbc:mysql://localhost:3306/subhash","root",“Subhash");
 if (con != null)
 System.out.println("Connection Successful");
else
 System.out.println("Not Connected");
 }
 catch(Exception e) {
 System.out.println(e);
 } } }
3) Create a statement
 Once a connection is obtained we can interact with
the database.
 The JDBC Statement, CallableStatement, and
PreparedStatement interfaces define the methods
and properties that enable you to send SQL or
PL/SQL commands and receive data from your
database.
 They also define methods that help bridge data
type differences between Java and SQL data types
used in a database.
 Statement
 Use this for general-purpose access to your
database.
 Useful when you are using static SQL statements at
runtime.
 The Statement interface cannot accept parameters.
3) Create the Statement object
 Statement stmt=con.createStatement();
4) 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.

 ResultSet rs=stmt.executeQuery("select * from emp");


 while(rs.next()){
 System.out.println(rs.getInt(1)+" "+rs.getString(2));
 }
Methods of Statement interface

Method Description
executes the query. It is used for create,
public int executeUpdate()
drop, insert, update, delete etc.
executes the select query. It returns an
public ResultSet executeQuery()
instance of ResultSet.
5) 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.
 con.close();
 import java.sql.*;
 class JavaApplication8{
 public static void main(String args[]){
 try{
 Class.forName("com.mysql.jdbc.Driver");
 Connection con=DriverManager.getConnection(
 "jdbc:mysql://localhost:3306/subhash","root",”Subhash");

 Statement stmt=con.createStatement();
 ResultSet rs=stmt.executeQuery("select * from
employee");
 while(rs.next())
 System.out.println(rs.getInt(1)+" "+rs.getString(2)+"
"+rs.getInt(3)+ " "+rs.getFloat(4)+" "+rs.getString(5));
 con.close();
 }catch(Exception e){ System.out.println(e);}
 }
 }
 import java.sql.*;
 class JavaApplication10{
 public static void main(String args[])throws Exception{
 Class.forName("com.mysql.jdbc.Driver");
 Connection con = DriverManager.getConnection(

 "jdbc:mysql://localhost:3306/subhash","root",“Subhash");

Statement stmt=con.createStatement();
 stmt.executeUpdate("insert into employee
values(3553,'Subhash2',12,56.12,'physics')");
 System.out.println("Data Inserted Successfully");
 con.close();
 }}
 PreparedStatement
 Use this when you plan to use the SQL statements
many times.
 The PreparedStatement interface accepts input
parameters at runtime.
 The PreparedStatement interface is a subinterface
of Statement. It is used to execute parameterized
query.
 PreparedStatement stmt=con.prepareStatement("insert
into employee values(?,?,?,?,?)");
 stmt.setInt(1,101);//1 specifies the first parameter in
the query
 stmt.setString(2,"Ratan");
 stmt.setFloat(3,79000.66f);
 stmt.setInt(4,27);
 stmt.setString(5,"Chemistry");
 int i=stmt.executeUpdate();
Methods of PreparedStatement interface

Method Description
public void setInt(int paramIndex, int sets the integer value to the given
value) parameter index.
public void setString(int paramIndex, sets the String value to the given
String value) parameter index.
public void setFloat(int paramIndex, sets the float value to the given
float value) parameter index.
public void setDouble(int paramIndex, sets the double value to the given
double value) parameter index.
executes the query. It is used for create,
public int executeUpdate()
drop, insert, update, delete etc.
executes the select query. It returns an
public ResultSet executeQuery()
instance of ResultSet.
 CallableStatement
 Use this when you want to access the database
stored procedures.
 The CallableStatement interface can also accept
runtime input parameters.
How to get the instance of CallableStatement?

 CallableStatement stmt=con.prepareCall("{call myp


rocedure(?,?)}");
How to create and call procedure
 Create procedure test1()
 Insert into employee values(12,”subhash”,23.55,26,
‘math’)
 ;

 Call test1();
JDBC Driver

 JDBC Driver is a software component that enables java


application to interact with the database.
 There are 4 types of JDBC drivers:
 JDBC-ODBC bridge driver

 Native-API driver (partially java driver)

 Network Protocol driver (fully java driver)

 Thin driver (fully java driver)

Class.forName("com.mysql.jdbc.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.
 In Java 7, the JDBC-ODBC Bridge has been removed.
1) JDBC-ODBC bridge driver

Class.forName("com.mysql.jdbc.Driver");
 Advantages:
 easy to use.
 can be easily connected to any database.
 Disadvantages:
 Performance degraded because JDBC method call is
converted into the ODBC function calls.
 The ODBC driver needs to be installed on the client machine.
Type 2
 In a Type 2 driver, JDBC API calls are converted
into native C/C++ API calls, which are unique to the
database.
 These drivers are 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.
2) Native-API driver

The Oracle Call Interface (OCI) driver is an


example of a Type 2 driver.
 Advantage:
 performance upgraded than JDBC-ODBC bridge
driver.
 Disadvantage:
 The Native driver needs to be installed on the each
client machine.
 The Vendor client library needs to be installed on
client machine.
3) Network Protocol driver

Your application server might use a Type 1, 2, or 4 driver


to communicate with the database
 The Network Protocol driver uses a three-tier
approach middleware (application server) that
converts JDBC calls directly or indirectly into the
vendor-specific database protocol.
 This kind of driver is extremely flexible, since it
requires no code installed on the client and a single
driver can actually provide access to multiple
databases.
 It is fully written in java.
 Advantage:
 No client side library is required because of application server
that can perform many tasks like auditing, load balancing,
logging etc.
 Disadvantages:
 Network support is required on client machine.
 Requires database-specific coding to be done in the middle
tier.
 Maintenance of Network Protocol driver becomes costly
because it requires database-specific coding to be done in the
middle tier.
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:
 Better performance than all other drivers.
 No software is required at client side or server side.
 Disadvantage:
 Drivers depend on the Database.
Which Driver should be Used?
 If you are accessing one type of database, such as
Oracle, Sybase, or IBM, the preferred driver type is 4.
 If your Java application is accessing multiple types of
databases at the same time, type 3 is the preferred
driver.
 Type 2 drivers are useful in situations, where a type 3
or type 4 driver is not available yet for your database.
 The type 1 driver is not considered a deployment-level
driver, and is typically used for development and
testing purposes only.

You might also like