JDBC

Download as pdf or txt
Download as pdf or txt
You are on page 1of 8

JDBC

Java Database Connectivity (JDBC) is a Java-based API (Application Programming


Interface) which is used to connect Java application with the database and execute
queries within a database management system (DBMS).

It is included with the Java Development Kit (JDK).

1.

2.
3. JDBC Architecture:

Java Application: A java programs that runs stand alone in a client or server.

JDBC API: It Provides classes and interfaces to connect or communicate java


application with database.

JDBC Driver Manager: This class manages lists of database drivers. It ensures that
correct driver is used to access each data source.

JDBC Driver: This interface handles the communications with the database.

Key components of the JDBC API include:

DriverManager: The DriverManager class is used to manage a list of database drivers.


It establishes a connection to the database by selecting an appropriate driver from
the list based on the connection URL.

Connection: The Connection interface represents a connection to a database. It allows


you to create and manage Statement and PreparedStatement objects for executing SQL
queries and updates. Connections should be established using the
DriverManager.getConnection() method.

Statement: The Statement interface is used for executing simple SQL queries. It allows
you to execute SQL statements and retrieve results. There are three types of
statements in JDBC: Statement, PreparedStatement, and CallableStatement.

PreparedStatement: The PreparedStatement interface is a subinterface of Statement. It


is used for precompiled SQL statements, which can improve performance and security
by preventing SQL injection.

CallableStatement: The CallableStatement interface is used for executing stored


procedures in the database.

ResultSet: The ResultSet interface represents the result set of a SQL query. It provides
methods for accessing and processing the query results.

SQLException: The SQLException class is an exception class that handles database-


related errors. It provides information about the error that occurred during database
operations.

Step to Connect Database:

1. Register driver class: Class.forName("com.mysql.cj.jdbc.Driver");


2. Creating Connection Object: connection = DriverManager.getConnection(jdbcURL,
username, password);
3. Creating Statement Object: statement = connection.createStatement();
4. Executing Query: resultSet = statement.executeQuery(sqlQuery);
5. Closing Connection:resultSet.close();

A.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

public class MySQLJDBCDemo {


public static void main(String[] args) {
// Database connection parameters for MySQL
String jdbcURL = "jdbc:mysql://localhost:3306/your_database"; // Replace with
your database URL
String username = "your_username"; // Replace with your database username
String password = "your_password"; // Replace with your database password

// JDBC objects
Connection connection = null;
Statement statement = null;
ResultSet resultSet = null;

try {
// 1. Load the MySQL JDBC driver
Class.forName("com.mysql.cj.jdbc.Driver");
// 2. Establish a database connection
connection = DriverManager.getConnection(jdbcURL, username, password);

// 3. Create a SQL statement


statement = connection.createStatement();

// 4. Execute a SQL query (select data)


String sqlQuery = "SELECT * FROM your_table"; // Replace with your
table name
resultSet = statement.executeQuery(sqlQuery);

// 5. Process the query results


while (resultSet.next()) {
// Access and print the data from the result set
String column1 = resultSet.getString("column1"); // Replace with your
column names
String column2 = resultSet.getString("column2");
System.out.println("Column 1: " + column1 + ", Column 2: " +
column2);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
// 6. Close the resources in reverse order
try {
if (resultSet != null) resultSet.close();
if (statement != null) statement.close();
if (connection != null) connection.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}

B.

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

public class JDBCApiExample {


public static void main(String[] args) {
String jdbcURL = "jdbc:mysql://localhost:3306/your_database";
String username = "your_username";
String password = "your_password";
try {
// Establish a database connection
Connection connection = DriverManager.getConnection(jdbcURL, username,
password);

// Create a statement
Statement statement = connection.createStatement();

// Execute a SQL query


String sqlQuery = "SELECT * FROM your_table";
ResultSet resultSet = statement.executeQuery(sqlQuery);

// Process the query results


while (resultSet.next()) {
String column1 = resultSet.getString("column1");
String column2 = resultSet.getString("column2");
System.out.println("Column 1: " + column1 + ", Column 2: " +
column2);
}

// Close resources
resultSet.close();
statement.close();
connection.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}

-- Create a Users table


CREATE TABLE Users (
UserID INT PRIMARY KEY,
FirstName VARCHAR(50),
LastName VARCHAR(50),
Age INT
);

-- Insert data into the Users table


INSERT INTO Users (UserID, FirstName, LastName, Age)
VALUES (1, 'John', 'Doe', 30);

INSERT INTO Users (UserID, FirstName, LastName, Age)


VALUES (2, 'Jane', 'Smith', 28);
-- Retrieve data from the Users table
SELECT * FROM Users;

-- Update the age of the user with UserID 1


UPDATE Users
SET Age = 31
WHERE UserID = 1;

-- Delete the user with UserID 2


DELETE FROM Users
WHERE UserID = 2;

Java 8 introduced several significant features, with functional interfaces and lambda
expressions being among the most notable ones. These features enable a more
functional programming style in Java, making it easier to write cleaner and more
concise code. Let's dive into each of these features:

Functional Interfaces:

A functional interface is an interface that contains only one abstract method. Java 8
introduced the @FunctionalInterface annotation to indicate that an interface is a
functional interface. Functional interfaces are a crucial concept for using lambda
expressions effectively.

For example, the java.util.function package in Java 8 provides a set of predefined


functional interfaces, such as:

Predicate: Represents a boolean-valued function that takes one argument.


Function: Represents a function that takes one argument and produces a result.
Consumer: Represents an operation that takes one argument and returns no result.
Supplier: Represents a supplier of results.

Here's an example of a simple functional interface:

java
@FunctionalInterface
interface MyFunctionalInterface {
void myMethod();
}

Lambda Expressions:

Lambda expressions are a concise way to define anonymous functions (or lambda
functions) in Java. They allow you to treat functionality as a method argument or
code as data. Lambda expressions are particularly useful when working with
functional interfaces.
The syntax for a lambda expression is as follows:

or
(parameter list) -> expression

or

(parameter list) -> { statements; }

For example, let's create a Predicate using a lambda expression to check if a number
is even:

java
Predicate<Integer> isEven = (number) -> number % 2 == 0;

Method References:

Method references provide a shorthand notation to call a method by referring to it


with the help of the :: operator. They are often used in conjunction with functional
interfaces and lambda expressions. There are four types of method references:

Reference to a static method


Reference to an instance method of a particular object
Reference to an instance method of an arbitrary object of a particular type
Reference to a constructor

Here's an example of using a method reference to create a Consumer to print the


elements of a list:

java
List<String> names = Arrays.asList("Alice", "Bob", "Charlie");
names.forEach(System.out::println);

Default and Static Methods in Interfaces:

Java 8 also introduced the ability to define default and static methods within
interfaces. Default methods provide a default implementation for interface methods,
allowing backward compatibility with existing classes. Static methods in interfaces are
used for utility methods related to the interface.

Here's an example of a default method in an interface:

java
interface MyInterface {
void abstractMethod();

default void defaultMethod() {


System.out.println("Default method implementation");
}
}

Java 8's functional interfaces, lambda expressions, and method references make it
easier to write more expressive and concise code, particularly when working with
collections, streams, and other functional programming paradigms. These features
enable a more versatile and modern programming style in Java.

You might also like