0% found this document useful (0 votes)
90 views

Chapter Six Java Database Connectivity: Debre Markos University Department of Computer Science

The document discusses Java Database Connectivity (JDBC), which provides a standard interface for connecting Java applications to various databases. It describes the basic components of JDBC including DriverManager, Driver, Connection, Statement, and ResultSet. It outlines the common steps to use a database in Java applications: importing drivers, establishing a connection, creating statements, executing queries, processing result sets, and closing connections. Finally, it provides examples of basic JDBC operations like insert, select, update, and delete.

Uploaded by

Mehari Temesgen
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
90 views

Chapter Six Java Database Connectivity: Debre Markos University Department of Computer Science

The document discusses Java Database Connectivity (JDBC), which provides a standard interface for connecting Java applications to various databases. It describes the basic components of JDBC including DriverManager, Driver, Connection, Statement, and ResultSet. It outlines the common steps to use a database in Java applications: importing drivers, establishing a connection, creating statements, executing queries, processing result sets, and closing connections. Finally, it provides examples of basic JDBC operations like insert, select, update, and delete.

Uploaded by

Mehari Temesgen
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 24

Debre Markos University

Department of Computer Science

Chapter Six
Java Database Connectivity

Advanced Programming(CoSc2084)

03/18/2021
What is 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.

* JDBC is an interface which allows Java code to execute SQL statements


inside relational databases.

* The JDBC library includes APIs for each of the tasks commonly
associated with database usage:

* Making a connection to a database


* Creating SQL or MySQL statements
* Executing that SQL or MySQL queries in the database
* Viewing & Modifying the resulting records
…..…
* JDBC API allows Java programs to connect with DBs
* Provides cross-vendor connectivity and data access across
relational databases from different vendors

* Classes and interfaces allow users to access the database in a


standard way

* The JVM uses the JDBC driver to translate generalized JDBC


calls into vendor specific database calls
………
*The driver is the piece of software that knows how to
talk to the actual database server.

*To load the driver, you just load the appropriate class;
a static block in the driver class itself automatically
makes a driver instance and registers it with the JDBC
driver manager.
………
*One of the beauties of the JDBC approach is that the
database server requires no changes whatsoever.

*Instead, the JDBC driver (which is on the client) translates


calls written in the Java programming language into the
native format required by the server.

*This approach means that you have to obtain a JDBC driver


specific to the database you are using and that you will need
to check the vendor’s documentation for the fully qualified
class name to use.
Common JDBC driver implementations
………
* The above figure illustrates two common JDBC driver
implementations.
* The first approach is a JDBC-ODBC bridge, and the second
approach is a pure Java implementation.
* A driver that uses the JDBC-ODBC bridge approach is known as
a Type I driver.
* Since many databases support Open DataBase Connectivity
(ODBC) access, the JDK includes a JDBC-ODBC bridge to
connect to databases.
* However, you should use the vendor’s pure Java driver, if
available, because the JDBC-ODBC driver implementation is
slower than a pure Java implementation. Pure Java drivers are
known as Type IV.
Common JDBC Components
* 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 sub
protocol 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
Basic steps to use a database in Java

* All JDBC programs do the following basic steps:


* Step 1) import and load the JDBC driver
* Step 2) .Establish a connection
* Step 3) .Create JDBC Statements
* Step 4) .Execute SQL Statements

* Step 5) .GET ResultSet

* Step 6) .Close connections


Creating JDBC Application

* There are six steps involved in building a JDBC application.


* Import the packages:
* This requires that you include the packages containing the JDBC
classes needed for database programming.

* Most often, using import java.sql.* will suffice as follows:


//STEP 1. Import required packages and load the JDBC driver

* import java.sql.*;
* To load driver go to project library and add jar file mysql
connector.
………
//STEP 2: Establish a connection

*In order to connect to database


*Make the connection
*Code snippet for connecting to MYSQL
Import java.sql.*;
String dbURL = “jdbc:mysql;//localhost:3306/db_name”;
String user = “user_name”;
String pass =”password”;

Connection myConn = DriverManager.getConnection(dbUrl, user.


Pass);
………
//STEP 3: Create JDBC Statements

*Creates a Statement object for sending SQL statements to the


database

*It will be used later to execute SQL query


Import java.sql.*;
String dbURL = “jdbc:mysql;//localhost:3306/db_name”;
String user = “user_name”;
String pass =”password”;
Connection myConn = DriverManager.getConnection(dbUrl, user.
Pass);

Statement myStmt = myConn.createStatement();


………
//STEP 4: Executing SQL Statements

*Process the result set


*Result set is initially placed before firs row
*Method: ResultSet.next()
* Moves forward one row
* Returns true if there are more rows to process
* Looping though a result set …….
*ResultSet myRs = myStmt.executeQuery(“SELECT * FROM
employee”);
While (myRs.next()){
// read data from each row
………
*Collection of methods for reading data
*getXXX(columnName)
*getXXX(columnIndex) one – based

…….
ResultSetmyRs = myStmt.executeQuery(“SELECT * FROM employee”);
While (myRs.next()){
System.out.println(myRs.getString(“last_name”));

System.out.println(myRs.getString(“First_name”));
}
………
//STEP 5: Get ResultSet
String queryLehigh = "select * from Lehigh";

ResultSet rs = Stmt.executeQuery(queryLehigh);

//What does this statement do?

while (rs.next()) {

int ssn = rs.getInt("SSN");

String name = rs.getString("NAME");

int marks = rs.getInt("MARKS");

}
………

//STEP 6: Close connection

rs.close();

stmt.close();

conn.close();
Sample JDBC Program

*Based on the above steps, we can have following


consolidated sample code which we can use as a
template while writing our JDBC code:

*This sample code has been written based on the


environment and database setup done in Environment
chapter.
Example
1. Insert Operation
packagejdbcdemo;
importjava.sql.*;
publicclass Insert {
publicstaticvoid main(String[] args) {
String url= "jdbc:mysql://localhost:3306/demo";
String user = "root";
String pass= "root";
try {
//1 get a connection to database
Connection myConn = DriverManager.getConnection(url, user, pass);
//crate statement
Statement myStmt = myConn.createStatement();
//3. execute SQL insert
String sql = "insert into employee"+"(last_name, first_name,
email)"+"values('betty','hab','[email protected]')";
………
myStmt.executeUpdate(sql);

System.out.println("insert complete.");

catch (Exception exc){

exc.printStackTrace();

// TODO code application logic here

}}
2. Selection Operation
packagejdbcdemo; 
importjava.sql.*;
publicclass Driver {
publicstaticvoid main(String[] args) {
try {
Connection myConn =
DriverManager.getConnection("jdbc:mysql://localhost:3306/demo","root","root");
Statement myStmt = myConn.createStatement();
ResultSet myRs = myStmt.executeQuery("select * from employee");
while(myRs.next()){ System.out.println(myRs.getString("last_name")
+","+myRs.getString("first_name")); } }
catch (Exception exc){
exc.printStackTrace();
} }}
3. delete operation
importjava.sql.*;
public class DeleteJava {
public static void main(String[] args) {
String url= "jdbc:mysql://localhost:3306/demo";
String user = "root";
String pass= "root";
try {
//1 get a connection to database
Connection myConn = DriverManager.getConnection(url, user, pass);
//crate statement
Statement myStmt = myConn.createStatement();
//3. execute SQL insert
String sql = "delete from employee where last_name='abebe'";
Int rowsAffected=myStmt.executeUpdate(sql);
System.out.println("Rows affected:"+rowsAffected);
System.out.println("Delete complete"); }
catch (Exception exc){
exc.printStackTrace();
} }}
4. Update Operation
packagejdbcdemo; 
importjava.sql.*;
publicclassUpdateStm {
publicstaticvoid main(String[] args) {
String url= "jdbc:mysql://localhost:3306/demo";
String user = "root";
String pass= "root";
try {
//1 get a connection to database
Connection myConn = DriverManager.getConnection(url, user,
pass);
//crate statement
Statement myStmt = myConn.createStatement();
………
//3. execute SQL insert
String sql = "update employee"
+" set email= 'kebede'"
+"where id=4";
myStmt.executeUpdate(sql);
System.out.println("Update complete.");
}
catch (Exception exc){
exc.printStackTrace();
}
}
}
OU
K Y
A N
TH
RY
VE
! !
C H
MU

03/18/2021

You might also like