0% found this document useful (0 votes)
15 views20 pages

ch4 - JDBC Basics

Uploaded by

dorarali369
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views20 pages

ch4 - JDBC Basics

Uploaded by

dorarali369
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 20

COURSE NAME : ADVANCED OBJECT ORIENTED

PROGRAMMING
COURSE CODE : 223CCS-3

CHAPTER 4: JDBC BASICS


SUBJECT COORDINATOR: MRS. MARIYAM AYSHA BIVI
SUBJECT TEACHERS: MR. OMER BIN HUSSAIN
MS. SHUMUKH HUSSAIN
DEPARTMENT OF COMPUTER SCIENCE
KING KHALID UNIVERSITY
ABHA, KSA.

Chapter No TOPICS Page Number Book Reference


JDBC Concepts and Terminology 1275 – 1277 TEXT BOOK 2: JAVA:
Tables 1278 – 1279 The Complete
Introducing SQL 1280 – 1285 Reference– Eleventh
SQL Statements 1286 – 1291 Edition, by Herbert
4
Schildt, 2019, McGraw-
The JDBC Package 1292 – 1298
Hill Education
JDBC Drivers 1300 – 1302
(Publisher). Chapter 24
Statement & Result Set Objects 1303 – 1308
CHAPTER 4 : JDBC BASICS

 JDBC Concepts and Terminology


 Tables

 Introducing SQL

 SQL Statements

 The JDBC Package

 JDBC Drivers

 Statement & Result Set Objects

 Sample Programs

2
4.1 JDBC CONCEPTS AND TERMINOLOGY
 Data access is the process of retrieving or manipulating data that is taken from a
remote or local data source.
 Data sources don’t have to be relational. Common examples of data sources
 A remote relational database on a server—for example, SQL Server
 A local relational database on your computer—for example, Personal Oracle or
Microsoft Access
 A text file on your computer
 A spreadsheet
 A remote mainframe/midrange host providing data access
 An online information service (such as a stock market ticker, for example)
 JDBC : an interface to relational data sources.The Java Database Connectivity
(JDBC) library provides the means to execute SQL statements within a Java
program to access and operate on a relational database.
 The library is implemented in the java.sql package.
 SQL( Structured Query Language is a declarative language,which means that SQL
statements tell the database server what you want to do, but not how it should be
done—the how is up to the server. 3
 Database engine: Each SQL command is analyzed by the database server, and the
operation it describes is carried out by a separate piece of software that is usually referred
4.2 TABLES
 A relational database consists of a number of tables.
 a Table is a collection of rows conforming to the specifications of the corresponding
columns, and the table is called a relation.

 Table Column: a table behaves as if it is a rectangular grid of cells. The grid has a given
number of columns and an arbitrary number of rows. Each column of cells in the grid
stores data of a particular kind. Not only is the data of a particular data type, but it is also
a specific category of information specified by the field name
 Table Column: Each row in a table is the collection of data elements that make up an
entity referred to as a tuple/record,.The term recordset is used to describe a collection of
rows that is produced by executing an SQL command.
 Database Catalog(database system tables):. System tables are used to store information
about the databases, the tables, and the composition of those tables, rather than storing
application data. The catalog can be queried to find out what tables are available from4 a
data source, what columns are defined for a given table, and so forth.
 Data Dictionary(MetaData) : The data describing the contents of a database
4.3 INTRODUCING SQL
 SQL Data Types

5
4.4 SQL STATEMENTS
 The InetAddress class is used to encapsulate both the numerical IP address and the
domain name for that address
Most SQL statements, and certainly the ones you’ll be using, fall neatly into two groups:
 Data Definition Language (DDL) statements that are used to describe the tables and the
data they contain.(CREATE TABLE and ALTER TABLE.)
 Data Manipulation Language (DML) statements that are used to operate on data in the
database. DML can be further divided into two groups:
❑ SELECT statements—Statements that return a set of results
❑ Everything else—Statements that don’t return a set of results
 CREATE STATEMENT :
CREATE TABLE authors ( authid INT NOT NULL PRIMARY KEY, lastname CHAR(25)
NOT NULL,firstname CHAR(15),address1 CHAR(25),address2 CHAR(25),
city CHAR(25),state_prov CHAR(25),zipcode CHAR(10),country CHAR(15),
phone CHAR(20),fax CHAR(20),email CHAR(25));
 INSERT STATEMENT :
INSERT INTO books (isbn, title, pub_code) VALUES (‘186100088X’, ‘Beginning Visual
C++ 6’, ‘WROX’)
when no columns are specified in an INSERT statement, SQL assumes that the values
following the VALUES keyword correspond to each column in the order that they were 6
specified when the table was created.
INSERT INTO books VALUES (‘186100088X’, ‘Beginning Visual C++ 6’, ‘WROX’)
4.4 SQL STATEMENTS(CONT…)
 SELECT STATEMENT :
SELECT firstname, lastname, authid FROM authors
Column aliases appear after the column names in the SELECT statement following the
keyword AS:
SELECT firstname, lastname, authid AS author_identifier FROM authors

specify the columns as * to indicate that you want to select all the columns in a table.
SELECT * FROM authors

WHERE clauses are used to filter the set of rows produced as the result of a SELECT operation
SELECT lastname, firstname FROM authors WHERE country = ‘UK’

multiple criteria for row selection in a WHERE clause


SELECT lastname, firstname, phone FROM authors WHERE country = ‘UK’
AND email IS NOT NULL

a SELECT statement—a table join.


a list of all authors and the books they have written.
SELECT a.lastname, a.firstname, b.title
FROM authors a, books b, auth_books ab 7
WHERE a.authid = ab.authid
AND b.isbn = ab.isbn
4.4 SQL STATEMENTS(CONT…)
 UPDATE STATEMENT :
UPDATE statements provide a way of modifying existing data in a table.

update the author record to reflect a change in last name for the author with the ID of 27.
UPDATE authors SET lastname = ‘Burk’ WHERE authid = 27
 DELETE STATEMENT :
DELETE statements provide a way of deleting particular rows from tables in a database.
DELETE FROM books WHERE isbn = ‘0131259075’

8
4.5 JDBC PACKAGE
 JDBC manages to operate with a variety of different relational database systems by having
an implementation of the JDBC interface for each specific database—a driver. This handles
the mapping of Java method calls in the JDBC classes to the database API.

MS Access

 Relating JDBC to ODBC


One of the fundamental principles of JDBC’s design was to make it practical to build JDBC
drivers based on other database APIs. There is a very close mapping between the JDBC
architecture and API and the Open DataBase Connectivity (ODBC)

9
4.5 JDBC PACKAGE(CONT…)
Setting Up a Database
 Start| Settings | Control Panel and then double-clicking the ODBC Data Sources icon.
 Select the System DSN tab and click the Add... button In the list box select Microsoft
Access Driver (*.mdb) and then click Finish.
 In next dialog box ODBC Microsoft Access Setup. In the Data Source Name text box at the
top of the dialog, type in College. Type Description text field.
 In the Database section of the dialog, click the Select button, and in the file browsing
dialog box that comes up, find and select your saved version of myDB.mdb
 The System DSN section of the initial ODBC Data Source Administrator dialog should now
have myDB.mdb in the list of system data sources available. Click the OK button at the
bottom of the dialog to exit.
DriverManager
 Set the “jdbc.drivers” system property
System.setProperty(“jdbc.drivers”,”sun.jdbc.odbc.JdbcOdbcDriver”);
list all your system properties as follows:
System.getProperties().list(System.out); // List all properties
To include the driver to use, load the driver explicitly by calling the static forName() method
in the Class class and passing a String object as an argument containing the driver class name.
Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”); // Load the ODBC driver
The forName() method can throw an exception of type ClassNotFoundException if the driver 1
class cannot be found, and this must be caught; so a call to the function has to appear in0a try
block with an appropriate catch block.
4.5 JDBC PACKAGE(CONT…)
Creating a Connection to a Data Source
A connection to a specific data source is represented by an object of a class that implements
the java.sql.Connection interface.
. Connection databaseConnection = DriverManager.getConnection(source);
URLs and JDBC
URLs to identify the locations of both drivers and data sources
jdbc:subprotocol:data_source_identifier

1
1
4.6 JDBC DRIVERS
 When the DriverManager class has been loaded, it is then possible to connect to a data
source using a particular driver.
 A driver is represented by an object of type java.sql.Driver. Driver implementations
come in four flavors:
❑ JDBC-ODBC Bridge driver
The JDBC-ODBC Bridge—”sun.jdbc.odbc.JdbcOdbcDriver”—is included with the
JDK, and it enables Java applications to access data through drivers written to the
ODBC standard.
❑ Native API/partly Java
This class of driver is quite similar to the bridge driver. It consists of Java code that
accesses data through native methods—
❑ Net protocol all-Java client
This class of driver is implemented as “middleware,” with the client driver
completely implemented in Java. This client driver communicates with a separate
middleware component (usually through TCP/IP), which translates JDBC requests
into database access calls.
❑ Native protocol all-Java
This class of driver communicates directly to the database server using the server’s
native protocol.
1
2
4.7 STATEMENT & RESULT SET OBJECTS
Statement Objects
 A java.sql.Statement object is an object of a class that implements the Statement
interface. When a Statement object is created, it provides a workspace for you to create
an SQL query, execute it, and retrieve any results that are returned.
ResultSet results = statement.executeQuery(
“SELECT lastname, firstname FROM authors”);

ResultSet Object
 The results of executing an SQL query are returned in the form of an object that
implements the ResultSet interface and contains the table produced by the SQL query.
 The ResultSet object contains something called a cursor that you can manipulate to refer
to any particular row in the resultset. This initially points to a position immediately
preceding the first row.
 first(), last() : reset the cursor to the first or last row
 beforeFirst(),afterLast() : set the cursor position before the first row or after the last
 previous() : moves the cursor from its current position to the previous row.
 next() : moves the cursor from its current position to the next row.
 next() and previous() return true if the move is to a valid row and false if you fall off the
end
while(resultset.next()) { 1
// Process the row... 3
}
4.8 PROGRAM FOR DATABASE CONNECTION
PROGRAM 1: DBConnectionSample1.java
import java.sql.*;
public class DBConnectionSample1 {
public static void main(String args[]) {
try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con =DriverManager.getConnection("jdbc:odbc:college");
System.out.println("Connection is: "+con);
} catch(ClassNotFoundException cnfe) {
System.err.println(cnfe);
} catch(SQLException sqle) {
System.err.println(sqle);
}
}
}
OUTPUT OF PROGRAM 1:
Connection is:
sun.jdbc.odbc.JdbcOdbcConnection@1d58aae

Process completed.

14
4.8 PROGRAM FOR DATABASE CONNECTION(CONT…)
PROGRAM 2: DBConnectionSample2.java
import java.sql.*;
public class DBConnectionSample2 {
public static void main(String args[]) throws Exception {
//initialize your JDBC driver by calling the method Class.forName
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
//The method DriverManager.getConnection establishes a database connection.
//This method requires a database URL, which varies depending on your DBMS.
//Specify the name of an existing database to which you want to connect.*/
Connection con = DriverManager.getConnection("jdbc:odbc:College");
// A Statement is an interface that represents a SQL statement. */
Statement stmt = con.createStatement();
String query = "SELECT StudName, StudID, StudLevel FROM Student";
//String query = "select * from Student";
//To execute a query, call an execute method from Statement.
//The method executeQuery returns one ResultSet object,
// which is a table of data representing a database result set.*/
ResultSet rs = stmt.executeQuery(query);
while(rs.next()) {
String name = rs.getString("StudName");
int a= rs.getInt("StudID");
int b = rs.getInt("StudLevel");
System.out.println("Student Name: "+ name+"; Student Id: " + a + " Level: " + b);
} 15
/* Closing Connections */ OUTPUT OF PROGRAM 2:
con.close(); Student Name: Rahman; Student Id: 1001 Level: 4
Student Name: Basma; Student Id: 1002 Level: 4
}
Student Name: Nada; Student Id: 1237 Level: 7
4.8 PROGRAM FOR DATABASE CONNECTION(CONT…)
PROGRAM 3: DBConnectionSample3.java
import java.sql.*;
public class DBConnectionSample3 {
public static void main(String args[]) throws Exception {

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
System.out.println("Connected");
Connection con = DriverManager.getConnection("jdbc:odbc:FirstDataBase");
Statement stmt = con.createStatement();

String query = "SELECT * FROM Students";

ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
String t = rs.getString("FIRSTNAME");
int a= rs.getInt("LEVEL");
System.out.println("First name: " +t +" Level: "+a);
} con.close();}
}

OUTPUT OF PROGRAM 3:
Connected
First name: Abdul Level: 1
First name: Mohamed Level: 4 16
First name: Syed Level: 5

Process completed.
4.8 PROGRAM FOR CREATING TABLE
PROGRAM 4: DBCreateTable.java
import java.sql.*;
public class DBCreateTable {
public static void main(String args[]) throws Exception {
//DataBase Name : mydb.mdb
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection("jdbc:odbc:College");
Statement stmt = con.createStatement();
String sql = "CREATE TABLE Course" +
"(courseID INTEGER not NULL, " +
" courseName VARCHAR(255), " +
" creditH INTEGER, " +
" PRIMARY KEY (courseID))";
stmt.executeUpdate(sql);
con.close();
}}

BEFORE RUNNING PROGRAM 4: AFTER RUNNING PROGRAM 4:

17
4.8 PROGRAM FOR INSERTING RECORD IN TABLE
PROGRAM 5: DBInsertRecord.java
import java.sql.*;
public class DBInsertRecord {
public static void main(String args[]) throws Exception {
//mydb.mdb
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection("jdbc:odbc:College");
Statement stmt = con.createStatement();

String query1 = "INSERT INTO Student VALUES (1003, 'Asma',5)";


stmt.executeUpdate(query1);
con.close();
}}
BEFORE RUNNING PROGRAM 5: AFTER RUNNING PROGRAM 5:

18
4.8 PROGRAM FOR SEARCHING RECORD IN TABLE
PROGRAM 6: DBSearchRecord.java
import java.sql.*;
public class DBSearchRecord {
public static void main(String args[]) throws Exception {
//mydb.mdb
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection("jdbc:odbc:College");
Statement stmt = con.createStatement();

String query1 = "SELECT *FROM Student WHERE StudLevel = 4";

ResultSet rs = stmt.executeQuery(query1);

while(rs.next()) {
int a= rs.getInt("StudID");
String name = rs.getString("StudName");
int b = rs.getInt("StudLevel");
System.out.println("Student Name: "+ name+"; Student Id: " + a + " Level: " + b);
}
/* Closing Connections */
con.close();
}}
OUTPUT OF PROGRAM 6:
Student Name: Rahman; Student Id: 1001 Level: 4 19
Student Name: Basma; Student Id: 1002 Level: 4
Process completed..
4.8 PROGRAM FOR DELETING RECORD FROM TABLE
PROGRAM 7: DBDeleteRecord.java
import java.sql.*;
public class DBDeleteRecord {
public static void main(String args[]) throws Exception {
//mydb.mdb
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection("jdbc:odbc:College");
Statement stmt = con.createStatement();
String query1 = "DELETE FROM Student WHERE StudID = 1002";
stmt.executeUpdate(query1);

String query = "SELECT StudName, StudID, StudLevel FROM Student";


ResultSet rs = stmt.executeQuery(query);
while(rs.next()) {
int a= rs.getInt("StudID");
String name = rs.getString("StudName");
int b = rs.getInt("StudLevel");
System.out.println("Student Name: "+ name+"; Student Id: " + a + " Level: " + b);
}
/* Closing Connections */
con.close();
}}
OUTPUT OF PROGRAM 7:
Student Name: Rahman; Student Id: 1001 Level: 4 20
Student Name: Nada; Student Id: 1004 Level: 7
Student Name: Asma; Student Id: 1003 Level: 5
Process completed.

You might also like