0% found this document useful (0 votes)
5 views37 pages

Chap5.1 Databaseconnection

Chapter 5 discusses JDBC (Java Database Connectivity) for accessing MySQL databases, detailing the process of establishing a connection, executing SQL statements, and processing results. It outlines the JDBC architecture, key components, and the steps for creating JDBC applications, including importing packages, opening connections, creating statement objects, and cleaning up resources. The chapter also covers different types of JDBC statements, such as Statement, PreparedStatement, and CallableStatement, highlighting their use cases and advantages.

Uploaded by

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

Chap5.1 Databaseconnection

Chapter 5 discusses JDBC (Java Database Connectivity) for accessing MySQL databases, detailing the process of establishing a connection, executing SQL statements, and processing results. It outlines the JDBC architecture, key components, and the steps for creating JDBC applications, including importing packages, opening connections, creating statement objects, and cleaning up resources. The chapter also covers different types of JDBC statements, such as Statement, PreparedStatement, and CallableStatement, highlighting their use cases and advantages.

Uploaded by

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

Chapter 5

(Part 1)

Database Connection
Outline
• Topics: JDBC to MySQL Database Access
• Introduction
• Make a connection
• Execute a SQL select statement
Database Management
Systems (DBMS)
 A software that is specifically designed to store, retrieve,
and manipulate large amounts of data in an organized
and efficient manner.

 Once the data is stored using the database management


system, applications may be written in Java or other
languages to communicate with the DBMS.

 Rather than retrieving or manipulating the data directly,


applications can send instructions to the DBMS. The
DBMS carries out those instructions and sends the
results back to the application.
JDBC (Java Database Connectivity)
Introduction
• JDBC is a Java standard that provides the interface for
connecting from Java to relational databases.
• The JDBC standard is defined by Sun Microsystems and
implemented through the standard java.sql interfaces.
• This allows individual providers to implement and
extend the standard with their own JDBC drivers.
• 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 Library
• The JDBC library includes JDBC APIs for each of the
tasks commonly associated with database usage:
1. Making a connection to a database
2. Creating SQL or MySQL statements
3. Executing that SQL or MySQL queries in the
database
4. Viewing & Modifying the resulting records
5. Close the connection
JDBC API

• JDBC API is a Java API that can access any kind of


tabular data, especially data stored in a Relational
Database.
• JDBC works with Java on a variety of platforms,
such as Windows, Mac OS, and the various versions
of UNIX.
JDBC Architecture
• Java code calls JDBC library. JDBC loads a driver
• Driver talks to a particular database
• An example of a driver is Connector/J.
Database

Java Code JDBC


Driver
JDBC consists of two layers:
1. JDBC API
• the top layer
• the programming interface to structured query
language (SQL) which is the standard for accessing
relational databases
2. JDBC Driver and Manager API
• JDBC API communicates with the JDBC Driver Manager API
• JDBC API sends various SQL statements
• The manager communicates with the drivers (that actually
connect to the database and return the information from the
query)
6 Common JDBC Components
1. DriverManager: This class manages a list of database drivers.
2. Driver: This interface handles the communications with the
database server.
3. 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.
4. Statement : You use objects created from this interface to
submit the SQL statements to the database.
5. ResultSet: These objects hold data retrieved from a database
after you execute an SQL query using Statement objects. It
6. SQLException: This class handles any errors that occur in a
database application.
Creating JDBC Application
1. Estblish Connection
i. Import the packages − include the packages containing the JDBC
classes needed for database programming.
ii. Open a connection − Requires using the
DriverManager.getConnection() method to create a Connection
object, which represents a physical connection with the database.

2. Create a statement object − Requires using an object of type Statement


for building and submitting an SQL statement to the database.

3. Execute a query − Requires using the appropriate ResultSet method to


retrieve the data from the result set.

4. Process the result − Retrieve the value for a specific field from a specific
record

5. Clean up the environment − Requires explicitly closing all database


resources versus relying on the JVM's garbage collection.
Database Connection

Import the packages

Requires to include the packages containing the


JDBC classes needed for database programming.

By using import java.sql.*

//step 1: import package


import java.sql.*;

public class ExampleJavaConnectDB {


... //program codes
... //program codes
}
Database Connection

Open a connection
The Driver Class for MySQL must be loaded from
the mysql-connector JAR file location.

The mysql-connector JAR file can be download


from:

https://dev.mysql.com/downloads/connector/j
/

OR

https://mvnrepository.com/artifact/mysql/my
sql-connector-java
Database Connection
Open a Connection
• Before we can access data in a database, we must
open a connection to the MySQL server.
Class.forName("com.mysql.cj.jdbc.Driver");
Connection con = DriverManager.getConnection(URL,
login, password);

• Steps:
• Loading the driver for MySQL Server database:
• Class.forName(“com.mysql.cj.jdbc.Driver”); // depends on the
particular Driver
• Making Connection
• Connects to given JDBC URL with given user name and
password
• URL = “jdbc:mysql://host:3306/database_name”;
• Returns a connection object
Database Connection

Open a connection

//step 1: import package


import java.sql.*;
public class ExampleJavaConnectDB {
public static void main(String args[]){
//step 2(a): load mysql-connector jar file into library
//step 2(b): register the driver class
Class.forName("com.mysql.cj.jdbc.Driver");
//step 2(c): establish connection with the database
Connection conn = DriverManager.getConnection
("jdbc:mysql://localhost/employeedb", "root", "");
}
}
Example: TestConnection
Connection conn = null;
try {
Class.forName("com.mysql.cj.jdbc.Driver");
System.out.println("... Driver loaded.");
conn = DriverManager.getConnection
("jdbc:mysql://localhost/employeedb", "root", "");
if (conn != null)
System.out.println("...MySQL Server connected.");
else
System.out.println("Failed to make connection!");
} catch (Exception e) {
System.out.println(e);
} finally {
try {
if (conn != null)
conn.close();
} catch (Exception e) {};
}
If the output is:
• java.sql.SQLException: No suitable driver found for …
• Check the classpath if it has been set correctly.
Database Connection

Create the statement object


Requires using an object of type Statement for
building and submitting an SQL statement to the
database.

The createStatement() method of Connection


interface is used to create statement. The object of
statement is responsible to execute queries with
the database.

Example to create the statement object:

Statement stmt = conn.createStatement();


Database Connection

Execute a 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.

Example to execute query:

ResultSet rs = stmt.executeQuery("select * from


employeedb");
Executing a Statement

• A Statement object is used for executing a SQL statement and


obtaining the results produced by it.
• Steps:
• Create a Statement Object
• Execute the query
• To execute a query, call an execute method from
Statement:
1. executeQuery(): for select statements
• Execute a SQL statement that returns a single
ResultSet.

2. executeUpdate(): for insert/delete/update


statements
• Execute a SQL INSERT, UPDATE or DELETE
statement. Returns the number of rows changed
Database Connection

Process the result


The next() method of ResultSet interface is
used to retrieve a single record from the
result.

The getXXXXX() method can be used to get


the value of a specific column from the
record

Example:
rs.next();
int empID = rs.getInt(1);
//step 3: create the statement object
Statement stmt = conn.createStatement();
stmt.executeUpdate("INSERT into employeedb (empNo, empName,
emailAdd, mobPhoneNo) values ('UTHM001', 'zanes', 'zanes@uthm.edu.my',
'01812121212');"");
//step 4: Execute the query
ResultSet rs = stmt.executeQuery("SELECT empNo, empName, emailAdd,
mobPhoneNo from employeedb");
//use loop to fetch/retrieve all data from table
// ...
//step 5: clean-up environment
rs.close();
stmt.close();
conn.close();
ResultSet

• A ResultSet provides access to a table of data generated by


executing a Statement.
• Only one ResultSet per Statement can be open at once.
• The table rows are retrieved in sequence.
• A ResultSet maintains a cursor pointing to its current row of data.
• ResultSet Methods:
• boolean next()
• activates the next row
• the first call to next() activates the first row
• returns false if there are no more rows
• void close()
• disposes of the ResultSet
• allows you to re-use the Statement that created it
ResultSet Methods
• int findColumn(String columnName)
• looks up column index given column name
• int getInt(int columnIndex)
• double getDouble(int columnIndex)
• String getString(int columnIndex)
• Date getDate(int columnIndex)

• String getString(String columnName)


stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
String emp_name = rs.getString("empName");
...
}
Example:

• Print employees number and name from the


EMPLOYEES table:
• sql = "SELECT EMPNO, EMPNAME FROM
EMPLOYEES"

sql = "SELECT EMPNO, EMPNAME FROM EMPLOYEEDB"


...
stmt = conn.createStatement();
rs = stmt.executeQuery(sql);
if (rs != null) {
while (rs.next())
System.out.printf("%s, %s", rs.getString(1), rs.getString(2));
}
Database Connection

Clean up the environment

Close all the connection objects.

By closing connection object statement and


ResultSet will be closed automatically.

The close() method of Connection interface is


used to close the connection.

Example to close connection:


conn.close();
JDBC Statements
JDBC Statements
• Once a connection is obtained we can interact with
the database.
• The JDBC
1. Statement,
2. CallableStatement
3. PreparedStatement
interfaces define the methods and properties that
enable you to send SQL commands and receive
data from your database.
Interfaces Recommended Use
Statement Use the for general-purpose access to your
database. Useful when you are using static SQL
statements at runtime. The Statement
interface cannot accept parameters.

PreparedStatement Use the when you plan to use the SQL


statements many times. The
PreparedStatement interface accepts input
parameters at runtime.
CallableStatement Use the when you want to access the database
stored procedures. The CallableStatement
interface can also accept runtime input
parameters.
1. The Statement Objects

• Creating Statement Object


Statement stmt = null;
try
{
stmt = conn.createStatement( ); . . .
}
catch (SQLException e)
{...}
Closing Statement Object
Statement stmt = null;
try
{
stmt = conn.createStatement( ); . . .
}
catch (SQLException e)
{...}
finally
{
stmt.close();
}
2. The PreparedStatement
Objects
• The PreparedStatement interface extends the
Statement interface, which gives you added
functionality with a couple of advantages over a
generic Statement object.
• This statement gives you the flexibility of supplying
arguments dynamically.
Creating PreparedStatement Object
PreparedStatement pstmt = null;
try
{
String SQL =
"Update employeedb SET age = ? WHERE id = ?";
pstmt = conn.prepareStatement(SQL);
pstmt.setInt(1, 21);
pstmt.setInt(2, 101);
...
}
catch (SQLException e)
The CallableStatement Objects

• Just as a Connection object creates the Statement


and PreparedStatement objects, it also creates the
CallableStatement object, which would be used to
execute a call to a database stored procedure.
Creating CallableStatement Object

CallableStatement cstmt = null;


try
{
String SQL = "{call getEmpName (?, ?)}";
cstmt = conn.prepareCall (SQL);
cstmt.setInt(1, 5);
cstmt.setInt(2, 2);
}
catch (SQLException e)
{...}

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy