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

CH 6

Uploaded by

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

CH 6

Uploaded by

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

Chapter six

JDBC
 Database Systems – an Introduction
 Structured Query Language

 Installing and setting up JDBC

 Basic JDBC Programming concepts

 Populating a database

 Executing Queries

 Scrollable and Updateable Result Sets


 A database is an organized collection of data. It used to store structured
data.
 It is also used to organize the data in the form of a table, schema, views,
and reports, etc.
 Example: The MAU Database organizes the data about the admin, staff,
students, faculty and other.
 Using the database, you can easily retrieve, insert, update and delete the
information.
 SQL (Structured Query Language) is used to perform variety of
operations(CRUD) on the records stored in the database, such as
updating records, inserting records, deleting records, creating
and modifying database tables, views, etc.
 SQL is not a database system, but it is a query language.

 To perform the queries of SQL language on the stored data in the

database. You are required to install any database management


system in your systems, for example,
 Oracle

 MySQL

 MongoDB

 PostgreSQL etc.
 SQL commands are instructions. It is used to communicate with the
database. It is also used to perform specific tasks, functions, and queries of
data.
 SQL can perform various tasks like create a table, add data to tables, drop
the table, modify the table, set permission for users.
 The following are two main type of SQL command
1. Data Definition Language (DDL) – It define and manage the structure of a
database. It deals with the creation, modification, and deletion of database.
Defines and manages database structure.
2. Data Manipulation Language - used for manipulating data within database
table. It allows users to query, insert, update, and delete data. Manipulates
and manages data within tables.
 DDL changes the structure of the database like creating a table,
deleting a table, altering a table, etc.
 The following command are DDL
 Create – to create database and table.
 Drop – to delete database.
 Alter and other – modify an existing database object.
 CREATE It is used to create data base and a new table in the
database.
 SQL syntax: to create database
CREATE DATABASE databasename;
 Example: CREATE DATABASE stud;
 Syntax: to create table
CREATE TABLE table_name(COLUMN_NAMES DATATYPES []);
 Example:
CREATE TABLE student(id int, name varchar(20), age int);
 DROP: It is used to delete both database and the structure or
record stored in the table.
 SQL syntax: to delete database
DROP DATABASE databasename;
DROP DATABASE stud;

Syntax: To delete a table permanently from memory.
DROP TABLE table_name
 ALTER: It is used to alter the structure of the database. Used to add,
delete, or modify columns in an exiting table.
 Syntax: To add a new column in the table
ALTER TABLE table_name ADD column_name data_type;
E.g. ALTER TABLE Customers ADD Email varchar(255);
 Syntax: To drop or delete column in the table
ALTER TABLE table_name DROP COLUMN column_name;
E.g. ALTER TABLE Customers DROP COLUMN Email;
 Syntax: To rename column name in the table
ALTER TABLE table_name RENAME COLUMN old_name to new_name;
 DML commands are used to modify the database. It is
responsible for all form of changes in the database. It change
the content of database.
 The following command are DDL
o Insert - Adds new data (rows) into a table.
o Update - Modifies existing data in a table
o Select - Retrieves data from one or more tables.
o Delete - Removes data (rows) from a table
 INSERT: The INSERT statement is a SQL query. It is used to insert data into
the row of a table. To insert a new row into a table you must be your on schema
or INSERT privilege on the table.
 SQL syntax:
INSERT INTO table_name(COLUMN1, COLUMN1) VALUES
(VALUE1, VALUE2);
 Example

INSERT INTO student (name, age, department) VALUES ('John Doe', 30,
'Sales');
 UPDATE command is used to update or modify the value of a
column in the table. To modify existing data, use the UPDATE
statement.
 Syntax:
UPDATE table_name SET column1 = value1, column2 = value2 where condition;
 E.g. UPDATE student SET age = 31 WHERE id = 1;
 SELECT: This is the same as the projection operation of relational
algebra. To retrieve data from a table, use the SELECT statement. It is
used to select the attribute based on the condition described by WHERE
clause.
 Syntax:
SELECT * FROM table_name;
SELECT column1, column2 FROM table_name;
 In this statement which the asterisk (*) wildcard character indicates that
all columns from the student table should be retrieved.
 E.g.
SELECT * FROM student WHERE department = ‘SW’;
 The advantage of WHERE clause is to filter data. In the above example we
filter only SW department from student table.
 DELETE is used to remove one or more row from a table. To
delete rows from the table, it must be in your schema or you
must have delete privilege. It used to delete existing records in
a table.
 Syntax:
DELETE FROM table_name WHERE condition;
 E.g.
DELETE FROM student where id = 1;
 A SQL DELETE statement removes rows from a table.
 We can use operator( Comparison, logical and other) in SQL
command instruction.
 Comparison: =, >, <, <=, >= , !
 Logical: AND, OR, NOT
 LIKE operator –
 E.g. SELECT * FROM table_name WHERE name LIKE ‘A%';
 BETWEEN operator –
E.g. SELECT * FROM student WHERE age BETWEEN 25 AND 40;
 SQL sorting
 To sort the result set, use the ORDER BY clause
E.g. SELECT * FROM student ORDER BY age DESC;
 JDBC is the connectivity of java and database.
 It provide API that for updating, and querying relational database using SQL.
 Java programs interact with databases using the Java Database Connectivity
(JDBC) API.
 A JDBC driver enables Java applications to connect to a database in a
particular DBMS and allows you to manipulate that database using the JDBC
API.
 Industry standard interface for connecting to relational databases from Java
 Independent of any DBMS
 You can use JDBC to interact with a database from within a Java program.
JDBC acts as a bridge from your code to the database, as shown below
 JDBC consists of
 JDBC API – it provide the set of interface and class to interact with the
database. The java.sql package contains classes and interfaces for JDBC
API. For example
 JDBC API interface include Driver, Connection, Statement, Prepared
Statement Result Set interface and other.
 JDBC API include Driver Manager class, Types class and other
 JDBC Driver – it is a software component that allows Java application to
communicate with database.
JDBC
JDBC API

Database
JDBC Driver
 The following are required to develop JDBC
 JAVA editor(NEATBEAN, eclipse and other) and JDK
 MYSQL connector
 XAMP Server it has Apache, MYSQL, PHP and other

component and it support multiple plateform.


 Overview of step a Database With JDBC

Connect

Query

Process
Results

Close
 Driver is a software component that provides the facility to a
computer to communicate with hardware.
 JDBC is the software component that enables java application to
interact with database.
 Statically load driver with class class and its method forName();
Class.forName(“Driver Name”);
 Use the jdbc.drivers system property
 Every driver has its own name
◦ For example
 Mysql - com.mysql.jdbc.Driver
 Oracle - oracle.jdbc.driver.OracleDriver
 Handled by DriverManager Object
 DriverManager class provide the facility to create a connection
between a database and the appropriate driver .
 To open a database connection we can call getConnection()
method of DriverManager class.
 Syntax: getConnection() method accept JDBC url, username,
and password
Connection con = DriverManager.getConnection(url, username, password)
 url like (“jdbc:mysql://localhost:3306/DBname” )

 username “root”

 password “”

 Returns a Connection object. To display connection occurred or


not by using this return object.
 JDBC URLs
 JDBC uses a URL to identify the database connection
jdbc:subprotocol:source
 Each driver has its own subprotocol
 Each subprotocol has its own syntax for the source
 A Statement object is used for executing a SQL statement and
obtaining the results produced by it.
 Different types of Statements
◦ Statement
◦ PreparedStatement
 Statement
◦ Used for executing a simple SQL statement and return the result.
◦ To created a statement object we have call createStatement()
method on the connection interface.
◦ Syntax: Statement stat = con. createStatement();
 Creates precompiled SQL statements - more efficient than
Statement class b/c it improve performance and help to prevent
SQL injection attacker.
 Can also allow specifying parameters that can be filled during run
time.
 Usually used if the statements is going to execute more than once
 Created by prepareStatement() method on the connection
object
◦ Accepts the query
◦ returns a new PreparedStatement object
 The following are statement method
 executeQuery(String sql)

◦ Accepts SQL query for select


◦ Execute a SQL query that returns a single ResultSet
 executeUpdate(String sql)
◦ Execute a SQL DROP, INSERT, CREATE, UPDATE or
DELETE statement. Returns the number of rows changed.
 Execute()
◦ Execute a SQL statement that may return multiple results.
◦ Used to execute any type of SQL statement.
 A ResultSet provides access to a table of data generated by
executing a Statement. Used to retrieve data from a database
query.
 Only one ResultSet per Statement can be open at once.
 The table rows are retrieved in sequence.
 The 'next' method moves the cursor to the next row.
 Syntax:
ResultSet rs = stat.excuteQuery(“Query”);
ResultSet rs = stat.excuteQuery(“SELECT * from Stu”);
 boolean next()
◦ activates the next row
◦ the first call to next() activates the first row
◦ returns false if there are no more rows
 Type getType(int columnIndex)
◦ returns the given field as the given type
◦ fields indexed starting at 1 (not 0)
 Type getType(String columnName)
◦ same, but uses name of field
◦ less efficient
 int findColumn(String columnName)
◦ looks up column index given column name
• String getString(String columnName)
• boolean getBoolean(String columnName)
• byte getByte(String columnName)
• short getShort(String columnName)
• int getInt(String columnName)
• long getLong(String columnName)
• float getFloat(String columnName)
• double getDouble(String columnName)
• Date getDate(String columnName)
• Time getTime(String columnName)
• Close the ResultSet object
• void close()
– disposes of the ResultSet
– allows you to re-use the Statement that created it
– automatically called by most Statement methods
 Close the Statement Object
• void close()
 Close the connection
 void close()
• Driver Manager
– Loads, chooses drivers
• Driver
– connects to actual database.
• Connection
– a series of SQL statements to and from the DB
• Statement
– a single SQL statement
• Result Set
– the records returned from a Statement
import java.sql.*;
public class CreateTableExample {
public static void main(String[] args) {
// Define JDBC URL, username, and password
String url = "jdbc:mysql://localhost:3306/mydatabase";
// Replace with your database details
String username = "root"; // Replace with your username
String password = "password"; // Replace with your password
// SQL query to create a new table
String createTableSQL = "CREATE TABLE employees ("
+ "id INT NOT NULL AUTO_INCREMENT, "
+ "name VARCHAR(100), "
+ "age INT, "
+ "PRIMARY KEY (id));";
// Initialize Connection and Statement objects
Connection connection = null;
Statement statement = null;
try {
// Step 1: Establish the connection
connection = DriverManager.getConnection(url, username, password);
// Step 2: Create a Statement object
statement = connection.createStatement();
// Step 3: Execute the CREATE query
statement.executeUpdate(createTableSQL);
System.out.println("Table 'employees' created successfully.");
} catch (SQLException e) {
e.printStackTrace();
} finally {
// Step 4: Close resources
try {
if (statement != null) statement.close();
if (connection != null) connection.close();
} catch (SQLException e) {
e.printStackTrace();
}}}}
public static void main(String[] args) {
Class.forName("com.mysql.cj.jdbc.Driver"); //load driver
Connnect connect =
DriverManager.getConnection(“jdbc:mysql://localhost:3302/mydatabase”, “username”,
“password”); //establish connection
Statement statement = connect.createStatement(); //create statement
ResultSet resultset= statement.excuteQuery(“select * from my table”); //execute query
while(resultset.next()){ //process result
//retrieve data
int id = resultset.getInt(“id”);
String name = resultset.getString();
//process data
System.out.print(“ID” + id + “, name : “ + name);
} //close resource
Resultset.close();
Connect.close();
Statement.close();
}
import java.sql.*;
public class InsertAuthor {
public static void main(String[] args) {
try {
// Load the JDBC driver
Class.forName("com.mysql.cj.jdbc.Driver");
// Connect to the database
String url = "jdbc:mysql://localhost:3306/Books?user = myuser&password= mypassword";
Connection conn = DriverManager.getConnection(url);
// Create a PreparedStatement object to execute SQL statements
String query = "INSERT INTO sudent (firstName, lastName) VALUES (?, ?)";
PreparedStatement pstmt = conn.prepareStatement(query);
// Set the parameter values for the query
pstmt.setString(1, "John");
pstmt.setString(2, "Doe");
// Execute the query and get the number of rows affected
int rows = pstmt.executeUpdate();
System.out.println(rows + " row(s) inserted.");
// Close the PreparedStatement and Connection objects
pstmt.close();
conn.close();
} catch (Exception e) {
e.printStackTrace();
}}}
import java.sql.*;
public class UpdateExample {
public static void main(String[] args) {
// Define JDBC URL, username, and password
String url = "jdbc:mysql://localhost:3306/mydatabase"; // Replace with your database details
String username = "root"; // Replace with your username
String password = "password"; // Replace with your password
// SQL query to update employee's age
String updateSQL = "UPDATE employees SET age = ? WHERE id = ?";
// Initialize Connection and PreparedStatement objects
Connection connection = null;
PreparedStatement preparedStatement = null;
}
try {
// Step 1: Establish the connection
connection = DriverManager.getConnection(url, username, password);
// Step 2: Create a PreparedStatement object
preparedStatement = connection.prepareStatement(updateSQL);
// Step 3: Set the parameters for the UPDATE query
preparedStatement.setInt(1, 30); // Set age to 30
preparedStatement.setInt(2, 1); // Update the employee with id = 1
// Step 4: Execute the UPDATE query
int rowsAffected = preparedStatement.executeUpdate();
System.out.println("Rows affected: " + rowsAffected);
} catch (SQLException e) {
e.printStackTrace();
} finally {
// Step 5: Close resources
try {
if (preparedStatement != null)
preparedStatement.close();
if (connection != null) connection.close();
} catch (SQLException e) {
e.printStackTrace();
}}}
import java.sql.*;
public class DropTableExample {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/mydatabase"; // Replace with your database details
String username = "root"; // Replace with your username
String password = "password"; // Replace with your password
// SQL query to drop a table
String dropTableSQL = "DROP TABLE IF EXISTS employees";
// Initialize Connection and Statement objects
Connection connection = null;
Statement statement = null;
try {
// Step 1: Establish the connection
connection = DriverManager.getConnection(url, username, password);
// Step 2: Create a Statement object
statement = connection.createStatement();
// Step 3: Execute the DROP query
statement.executeUpdate(dropTableSQL);
System.out.println("Table 'employees' dropped successfully.");
} catch (SQLException e) {
e.printStackTrace();
} finally {
// Step 4: Close resources
try {
if (statement != null)
statement.close();
if (connection != null)
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}}}}

You might also like