UNIT-4
Q- EXPLAIN THE DIFFERENT TYPE OF DRIVES IN JDBC ?
JDBC (Java Database Connectivity) drivers are essential for connecting Java
aplications to databases. There are four main types of JDBC drivers:
Type 1: JDBC-ODBC Bridge Driver
This driver uses the ODBC driver to connect to the database.
It translates JDBC calls into ODBC calls.
It's not recommended for production use due to performance and reliability issues.
Type 2: Native-API Driver
This driver converts JDBC calls into database-specific calls using native libraries.
It requires native binary code on the client machine.
It's faster than Type 1 but still has dependency issues.
Type 3: Network Protocol Driver
This driver uses a middleware server to convert JDBC calls into database-specific
calls.
It allows for better scalability and flexibility.
It's suitable for internet-based applications.
Type 4: Thin Driver
This driver converts JDBC calls directly into database-specific calls using a pure Java
implementation.
It doesn't require any native libraries.
It's the most efficient and widely used driver type.
Each type has its own advantages and use cases, so the choice depends on your
specific requirements and environment.
Q-What do you understand by JDBC. Explain the architecture of JDBC with a neat and clean diagram.
JDBC (Java Database Connectivity) is an API (Application Programming Interface)
that allows Java applications to interact with databases. It provides a standard way
to connect to and interact with various databases, enabling developers to execute
SQL queries, retrieve results, and manage database connections.
Architecture of JDBC
The JDBC architecture consists of two main layers:
JDBC API: This layer provides the application-to-JDBC Manager connection. It
consists of interfaces and classes that Java applications use to interact with
databases.
JDBC Driver API: This layer provides the JDBC Manager-to-Driver connection. It
consists of driver implementations that communicate with the database.
Here's a simplified diagram of the JDBC architecture:
Java Application JDBC API JDBC Driver APIDatabase
In this architecture:
The Java Application uses the JDBC API to send SQL queries and retrieve results.
The JDBC API translates these requests into calls to the JDBC Driver API.
The JDBC Driver API communicates with the database to execute the queries and
return the results to the Java application.
Q-write and explain the steps for java database connectivity.
1. Import the JDBC Packages: This step involves importing the necessary JDBC classes and interfaces
required for database operations.
e.g import [Link].*;
2. Load and Register the JDBC Driver: The JDBC driver class is loaded into memory using
[Link](). This step is essential for establishing a connection with the database.
e.g [Link]("[Link]");
3. Establish a Connection: The [Link]() method is used to establish a connection
to the database. It requires the database URL, username, and password.
e.g Connection con = [Link]("jdbc:mysql://localhost:3306/dbname",
"username", "password");
4. Create a Statement: A Statement object is created using the Connection object. This object is used to
execute SQL queries.
e.g Statement stmt = [Link]();
5. Execute a Query: The [Link]() method is used to execute SQL queries. It returns a
ResultSet object containing the results of the query.
e.g ResultSet rs = [Link]("SELECT * FROM tablename");
6. Process the Result Set: The ResultSet object is used to iterate through the results of the query. The
[Link]() method moves the cursor to the next row, and the [Link]() method retrieves the value of
the specified column.
e.g while ([Link]()) {
[Link]([Link]("columnname"));}
7. Close the Connection: Finally, the ResultSet, Statement, and Connection objects are closed to free up
resources and avoid memory leaks.
e.g [Link]();
[Link]();
[Link]();
Q Explain any two SQL exception in JDBC.
[Link]
This is the base class for all SQL exceptions.
It provides information about database access errors or other errors.
It includes methods to retrieve the SQL state, error code, and detailed error message.
Example: try {
// Database operations
} catch (SQLException e) {
[Link]("SQLState: " + [Link]());
[Link]("Error Code: " + [Link]());
[Link]("Message: " + [Link]());}
2. SQLIntegrityConstraintViolationException
This exception is thrown when a database integrity constraint (such as a primary key or foreign key
constraint) is violated.
It is a subclass of SQLException.
Example: try {
// Insert operation that violates a primary key constraint
} catch (SQLIntegrityConstraintViolationException e) {
[Link]("Integrity Constraint Violation: " + [Link]());}
Q what is result set meta data. Explain with example.
ResultSetMetaData is an interface in the JDBC API that provides information about the types and
properties of the columns in a ResultSet object. It allows you to retrieve metadata about the columns,
such as column names, types, and sizes, without having to execute additional queries.
e.g
import [Link].*;
public class ResultSetMetaDataExample {
public static void main(String[] args) {
try {
// Load and register the JDBC driver
[Link]("[Link]");
// Establish a connection
Connection con = [Link]("jdbc:mysql://localhost:3306/dbname",
"username", "password");
// Create a statement
Statement stmt = [Link]();
// Execute a query
ResultSet rs = [Link]("SELECT * FROM tablename");
ResultSetMetaData rsmd = [Link]();
int columnCount = [Link]();
// Print column names and types
for (int i = 1; i <= columnCount; i++) {
String columnName = [Link](i);
String columnType = [Link](i);
[Link]("Column Name: " + columnName + ", Column Type: " + columnType); }
// Close the connection
[Link]();
[Link]();
[Link]();
} catch (Exception e) {
[Link](); } } }
Load and Register the JDBC Driver: The JDBC driver class is loaded into memory using
[Link]().
Establish a Connection: The [Link]() method is used to establish a
connection to the database.
Create a Statement: A Statement object is created using the Connection object.
Execute a Query: The [Link]() method is used to execute an SQL query, which
returns a ResultSet object.
Get ResultSetMetaData: The [Link]() method is used to retrieve the
ResultSetMetaData object.
Get the Number of Columns: The [Link]() method returns the
number of columns in the ResultSet.
Print Column Names and Types: A loop is used to iterate through the columns, and the
[Link]() and [Link]()
methods are used to retrieve and print the column names and types.
Close the Connection: Finally, the ResultSet, Statement, and Connection objects are closed to
free up resources.
Q write a java program to display and insert data ( string , integer, foat and date type) in/form
database where rows are atlest 15 in a table?
import [Link].*;
import [Link];
public class DatabaseExample {
public static void main(String[] args) {
try {
// Load and register the JDBC driver
[Link]("[Link]");
// Establish a connection
Connection con =
[Link]("jdbc:mysql://localhost:3306/dbname", "username",
"password");
// Create a statement
Statement stmt = [Link]();
// Create a table
String createTableSQL = "CREATE TABLE IF NOT EXISTS ExampleTable (" +
"id INT AUTO_INCREMENT PRIMARY KEY, " +
"name VARCHAR(50), " +
"age INT, " +
"salary FLOAT, " +
"joining_date DATE)";
[Link](createTableSQL);
// Insert data into the table
String insertSQL = "INSERT INTO ExampleTable (name, age, salary, joining_date)
VALUES (?, ?, ?, ?)";
PreparedStatement pstmt = [Link](insertSQL);
for (int i = 1; i <= 15; i++) {
[Link](1, "Name" + i);
[Link](2, 20 + i);
[Link](3, 30000.0f + (i * 1000));
[Link](4, new [Link](new Date().getTime()));
[Link]();
}
// Display data from the table
ResultSet rs = [Link]("SELECT * FROM ExampleTable");
while ([Link]()) {
int id = [Link]("id");
String name = [Link]("name");
int age = [Link]("age");
float salary = [Link]("salary");
Date joiningDate = [Link]("joining_date");
[Link]("ID: " + id + ", Name: " + name + ", Age: " + age + ", Salary: "
+ salary + ", Joining Date: " + joiningDate);
}
// Close the connection
[Link]();
[Link]();
[Link]();
[Link]();
} catch (Exception e) {
[Link](); } } }
Q what is use of jdbc in a high level programming. write a program to create table , insert data into
table , update data after searching the data and display sorted data?
JDBC (Java Database Connectivity) is crucial in high-level programming as it
provides a standard API for connecting Java applications to various databases. It
allows developers to execute SQL queries, retrieve results, and manage database
connections seamlessly. JDBC is widely used in enterprise applications, web
applications, and any scenario where database interaction is required.
import [Link].*;
public class JDBCExample {
public static void main(String[] args) {
try {
[Link]("[Link]");
Connection con =
[Link]("jdbc:mysql://localhost:3306/dbname", "username",
"password");
Statement stmt = [Link]();
String createTableSQL = "CREATE TABLE IF NOT EXISTS ExampleTable (" +
"id INT AUTO_INCREMENT PRIMARY KEY, " +
"name VARCHAR(50), " +
"age INT, " +
"salary FLOAT, " +
"joining_date DATE)";
[Link](createTableSQL);
String insertSQL = "INSERT INTO ExampleTable (name, age, salary,
joining_date) VALUES (?, ?, ?, ?)";
PreparedStatement pstmt = [Link](insertSQL);
for (int i = 1; i <= 15; i++) {
[Link](1, "Name" + i);
[Link](2, 20 + i);
[Link](3, 30000.0f + (i * 1000));
[Link](4, new [Link](new [Link]().getTime()));
[Link](); }
String updateSQL = "UPDATE ExampleTable SET salary = ? WHERE name
= ?";
pstmt = [Link](updateSQL);
[Link](1, 50000.0f);
[Link](2, "Name5");
[Link]();
ResultSet rs = [Link]("SELECT * FROM ExampleTable ORDER
BY name");
while ([Link]()) {
int id = [Link]("id");
String name = [Link]("name");
int age = [Link]("age");
float salary = [Link]("salary");
Date joiningDate = [Link]("joining_date");
[Link]("ID: " + id + ", Name: " + name + ", Age: " + age + ",
Salary: " + salary + ", Joining Date: " + joiningDate); }
[Link]();
[Link]();
[Link]();
[Link](); } catch (Exception e) {
[Link](); } } }
Q write a program to in java to add and update data into database where table student and column
are Sr_number integer type, name string type, fees float type. update will be done first you will search
by primary key?
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class StudentDatabase {
private static final String URL = "jdbc:mysql://localhost:3306/your_database";
private static final String USER = "your_username";
private static final String PASSWORD = "your_password";
public static void main(String[] args) {
try {
Connection connection = [Link](URL, USER, PASSWORD);
// Add a new student
addStudent(connection, 1, "John Doe", 1500.0f);
// Update student data
updateStudent(connection, 1, "John Smith", 2000.0f);
[Link]();
} catch (SQLException e) {
[Link](); } }
public static void addStudent(Connection connection, int srNumber, String name, float fees) throws
SQLException {
String insertSQL = "INSERT INTO student (Sr_number, name, fees) VALUES (?, ?, ?)";
try (PreparedStatement preparedStatement = [Link](insertSQL)) {
[Link](1, srNumber);
[Link](2, name);
[Link](3, fees);
[Link]();
[Link]("Student added successfully."); } }
public static void updateStudent(Connection connection, int srNumber, String name, float fees)
throws SQLException {
String selectSQL = "SELECT * FROM student WHERE Sr_number = ?";
try (PreparedStatement selectStatement = [Link](selectSQL)) {
[Link](1, srNumber);
ResultSet resultSet = [Link]();
if ([Link]()) {
String updateSQL = "UPDATE student SET name = ?, fees = ? WHERE Sr_number = ?";
try (PreparedStatement updateStatement = [Link](updateSQL)) {
[Link](1, name);
[Link](2, fees);
[Link](3, srNumber);
[Link]();
[Link]("Student updated successfully.");
}
} else {
[Link]("Student with Sr_number " + srNumber + " not found."); } } } }
Q write a program in java to update data in a table for a rollno. =101 using preparedstatement ?
import [Link];
import [Link];
import [Link];
import [Link];
public class UpdateStudentData {
private static final String URL = "jdbc:mysql://localhost:3306/your_database";
private static final String USER = "your_username";
private static final String PASSWORD = "your_password";
public static void main(String[] args) {
try {
Connection connection = [Link](URL, USER, PASSWORD);
// Update student data for rollno = 101
updateStudentData(connection, 101, "Jane Doe", 2500.0f);
[Link]();
} catch (SQLException e) {
[Link](); } }
public static void updateStudentData(Connection connection, int rollno, String name, float fees)
throws SQLException {
String updateSQL = "UPDATE student SET name = ?, fees = ? WHERE rollno = ?";
try (PreparedStatement preparedStatement = [Link](updateSQL)) {
[Link](1, name);
[Link](2, fees);
[Link](3, rollno);
int rowsAffected = [Link]();
if (rowsAffected > 0) {
[Link]("Student data updated successfully.");
} else {
[Link]("Student with rollno " + rollno + " not found."); } } } }
Q what do ypu mean by collection. write a program to store and display data in arraylist, vector ,
treeset and treemap collection?
import [Link];
import [Link];
import [Link];
import [Link];
public class CollectionExample {
public static void main(String[] args) {
// ArrayList
ArrayList<String> arrayList = new ArrayList<>();
[Link]("Apple");
[Link]("Banana");
[Link]("Cherry");
[Link]("ArrayList: " + arrayList);
// Vector
Vector<String> vector = new Vector<>();
[Link]("Dog");
[Link]("Elephant");
[Link]("Fox");
[Link]("Vector: " + vector);
// TreeSet
TreeSet<String> treeSet = new TreeSet<>();
[Link]("Grapes");
[Link]("Honeydew");
[Link]("Kiwi");
[Link]("TreeSet: " + treeSet);
// TreeMap
TreeMap<Integer, String> treeMap = new TreeMap<>();
[Link](1, "Lion");
[Link](2, "Tiger");
[Link](3, "Bear");
[Link]("TreeMap: " + treeMap); } }
Q what is jdbc. write a program in java to insert data into employee table { id,name, aadhar_card,
pan_card} and delete row for name "abc" and display the rest of data?
JDBC (Java Database Connectivity) is an API (Application Programming Interface) that allows Java
applications to interact with databases. It provides methods to connect to a database, execute SQL
queries, and retrieve results. JDBC is part of the Java Standard Edition platform and is widely used for
database operations in Java applications.
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class EmployeeDatabase {
private static final String URL = "jdbc:mysql://localhost:3306/your_database";
private static final String USER = "your_username";
private static final String PASSWORD = "your_password";
public static void main(String[] args) {
try {
Connection connection = [Link](URL, USER, PASSWORD);
// Insert data into employee table
insertEmployee(connection, 1, "John Doe", "123456789012", "ABCDE1234F");
insertEmployee(connection, 2, "abc", "987654321098", "FGHIJ5678K");
// Delete row where name is "abc"
deleteEmployeeByName(connection, "abc");
// Display remaining data
displayEmployees(connection);
[Link]();
} catch (SQLException e) {
[Link](); } }
public static void insertEmployee(Connection connection, int id, String name, String aadharCard,
String panCard) throws SQLException {
String insertSQL = "INSERT INTO employee (id, name, aadhar_card, pan_card) VALUES (?, ?, ?, ?)";
try (PreparedStatement preparedStatement = [Link](insertSQL)) {
[Link](1, id);
[Link](2, name);
[Link](3, aadharCard);
[Link](4, panCard);
[Link]();
[Link]("Employee added successfully."); } }
public static void deleteEmployeeByName(Connection connection, String name) throws SQLException
{
String deleteSQL = "DELETE FROM employee WHERE name = ?";
try (PreparedStatement preparedStatement = [Link](deleteSQL)) {
[Link](1, name);
int rowsAffected = [Link]();
if (rowsAffected > 0) {
[Link]("Employee with name '" + name + "' deleted successfully.");
} else {
[Link]("Employee with name '" + name + "' not found.");} } }
public static void displayEmployees(Connection connection) throws SQLException {
String selectSQL = "SELECT * FROM employee";
try (PreparedStatement preparedStatement = [Link](selectSQL)) {
ResultSet resultSet = [Link]();
while ([Link]()) {
int id = [Link]("id");
String name = [Link]("name");
String aadharCard = [Link]("aadhar_card");
String panCard = [Link]("pan_card");
[Link]("ID: " + id + ", Name: " + name + ", Aadhar Card: " + aadharCard + ", PAN
Card: " + panCard); } } } }
Q discuss various applications of jdbc?
Data Insertion: JDBC is used to insert data into databases. For example, adding new records to a
table.
Data Retrieval: It allows for querying databases to retrieve data. This is useful for applications that
need to display or process data from a database.
Data Update: JDBC can be used to update existing records in a database. This is essential for
applications that need to modify data.
Data Deletion: It provides the capability to delete records from a database, which is useful for
maintaining and managing data.
Transaction Management: JDBC supports transaction management, allowing multiple operations to
be executed as a single unit of work. This ensures data integrity and consistency.
Batch Processing: It allows for executing multiple SQL statements in a batch, which can improve
performance for bulk operations.
Metadata Retrieval: JDBC can retrieve metadata about the database, such as table structure, column
types, and database capabilities.
Stored Procedures: It supports calling stored procedures in the database, which can encapsulate
complex business logic.
Connection Pooling: JDBC can be used with connection pooling libraries to manage database
connections efficiently, improving application performance.
Database Migration: It can be used in tools and scripts for migrating data between different
databases.