MODULE 5
1. What are database drivers? Explain the different JDBC driver types. (10M)
Sol.
Definition:
2. Explain the different steps of JDBC process with code snippets for each step. (10M)
Sol.
3. Mention all steps to create the association b/w the database & JDBC/ODBC bridge.
(12M)
1. Install the Database: Install a suitable Database Management System (DBMS) on your
computer, such as MS Access, MySQL, or Oracle. This software is required to store, manage,
and retrieve data for your application.
2. Create the Database: Using the DBMS, create a new database and define tables with
appropriate columns, data types, and primary keys. Example: Create a table named students
with fields like id, name, and marks.
3. Add Data to the Tables: Insert sample records into your tables to ensure there's data to
query and test your connection. This helps verify that your connection and SQL statements are
working correctly.
4. Open ODBC Data Source Administrator: Go to: Control Panel > Administrative Tools >
ODBC Data Sources Choose 32-bit or 64-bit depending on your Java and DB version.
5. Create a DSN (Data Source Name): In the ODBC Administrator window:
Select User DSN or System DSN tab.
Click Add, choose a driver (e.g., Microsoft Access Driver), and set up the data source.
This links your database to a readable name.
6. Name the DSN: Assign a unique and meaningful name to your DSN (e.g., "studentDB"). This
name will be used as an identifier in your Java connection string.
7. Import JDBC Package: In your Java program, import the necessary JDBC classes:
import java.sql.*;
This provides access to interfaces like Connection, Statement, ResultSet, etc.
8. Load the JDBC-ODBC Driver: Load the JDBC-ODBC bridge driver class using:
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
This step registers the driver with the JDBC driver manager.
9. Establish the Connection: Connect to the database using the DriverManager:
Connection con = DriverManager.getConnection("jdbc:odbc:studentDB");
This establishes a connection to the database using the specified DSN.
10. Create Statement: Object Create a Statement object to send SQL commands to the
database:
Statement stmt = con.createStatement();
Alternatively, use PreparedStatement for dynamic or parameterized queries.
11. Execute Queries and Process Results: Run SQL queries and handle the result:
ResultSet rs = stmt.executeQuery("SELECT * FROM students");
while (rs.next()) {
System.out.println("Name: " + rs.getString("name"));
}
This loop prints each student's name retrieved from the database.
4. Write the java program to connect to database using URL and to connect database
using userID and password. (8M)
Sol.
package JDBCExample;
// 1. import sql package
import java.sql.*;
public class JDBCDemo {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/student"; // use the correct DB name and port
String uname = "root";
String pass = "seetha1234";
String query = "SELECT * FROM students";
try {
// 2. Load MySQL JDBC driver
Class.forName("com.mysql.cj.jdbc.Driver");
// 3. Connect to database
Connection con = DriverManager.getConnection(url, uname, pass);
// 4. Create statement and execute query
Statement st = con.createStatement();
// 5. Execute the query
ResultSet rs = st.executeQuery(query);
// 6. process and Display results
while (rs.next()) {
String name = rs.getString("name");
int age = rs.getInt("age");
String email = rs.getString("email");
System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("Email: " + email);
System.out.println("--------------- ---------");
}
// 7. Close resources
rs.close();
st.close();
con.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
package JDBCExample;
//1.import sql package
import java.sql.*;
public class JDBCDemo {
public static void main(String[] args) {
String url = "jdbc:odbc:Ex"; // JDBC/ODBC bridge URL
String uname = "orcl";
String pass = "tiger";
String query = "SELECT * FROM EMPLOYEE WHERE SALARY > 20000";
try {
// 2.Load JDBC/ODBC bridge driver
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
// 3. Connect to database
Connection con = DriverManager.getConnection(url, uname, pass);
// 4.Create statement and execute query
Statement st = con.createStatement();
// 5.Execute the query
ResultSet rs = st.executeQuery(query);
// 6.process and Display results
while (rs.next()) {
int empId = rs.getInt("EMP_ID");
String name = rs.getString("EMP_NAME");
int salary = rs.getInt("SALARY");
System.out.println("EMP ID: " + empId);
System.out.println("Name: " + name);
System.out.println("Salary: " + salary);
System.out.println("---------------------------");
}
// 7. Close resources
rs.close();
st.close();
con.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Output:
EMP ID: 101
Name: Kanha
Salary: 25000
---------------------------
EMP ID: 104
Name: Madhav
Salary: 31000
---------------------------
5. Write any two syntax of establishing a connection to the database.(4M)
Sol. Using Data source:
public class DataSourceExample {
public static void main(String[] args) {
try {
Context ctx = new InitialContext();
DataSource ds = (DataSource) ctx.lookup("jdbc/MyDataSource");
Connection conn = ds.getConnection();
System.out.println("Connection established successfully!");
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
6. What is connection pooling? Explain the same with neat diagram and code snippets.
(10M)
Sol.
Connection Pooling
Connection pooling is a database optimization technique that manages a pool of reusable
database connections.
Instead of opening and closing a new connection for every request, it reuses existing
connections, reducing the overhead of frequent connection creation.
This is especially useful in web applications with many users, as it improves performance,
reduces latency, and conserves database resources.
// Step 1: Access JNDI context
Context ctxt = new InitialContext();
// Step 2: Lookup the DataSource from the pool
DataSource pool = (DataSource) ctxt.lookup("java:comp/env/jdbc/pool");
// Step 3: Get a logical connection from the pool
Connection db = pool.getConnection();
// Step 4: Use the connection for DB operations
// db.executequery(select * from users);
// Step 5: Close the logical connection (returns to pool)
db.close();
7. With proper syntax describe three types of getConnection() methods.(6M)
Sol.
8. Explain the use of object in establishing the connection. Also write a program to call
stored procedures.(10M)
Sol.
9. Describe the following concepts: (10M)
(i) Scrollable ResultSet
(ii) Callable Statement
(iii) Transaction processing
(iv) Updatable ResultSet
(v) Prepared Statement
Sol.
(i) Scrollable ResultSet
A Scrollable ResultSet allows you to move the cursor both forward and backward, or to
a specific row.
Used with: ResultSet.TYPE_SCROLL_INSENSITIVE / TYPE_SCROLL_SENSITIVE
Code:
Connection con = DriverManager.getConnection(url, user, pass);
Statement stmt = con.createStatement(
ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
ResultSet rs = stmt.executeQuery("SELECT * FROM students");
rs.last(); // Move to last row
System.out.println("Last Student: " + rs.getString("name"));
rs.first(); // Move to first row
System.out.println("First Student: " + rs.getString("name"));
rs.previous(); // Move to previous row (if possible)
(ii) CallableStatement
Used to call stored procedures in the database.
Used for: ● Invoking pre-written database logic ● Accepts IN/OUT parameters
Code (MySQL stored procedure):
CREATE PROCEDURE getStudentName(IN id INT, OUT name VARCHAR(50))
BEGIN
SELECT student_name INTO name FROM students WHERE student_id = id;
END;
Java code:
CallableStatement cs = con.prepareCall("{call getStudentName(?, ?)}");
cs.setInt(1, 101); // IN parameter
cs.registerOutParameter(2, Types.VARCHAR); // OUT parameter
cs.execute();
System.out.println("Student Name: " + cs.getString(2));
(iii) Transaction Processing
A transaction is a group of SQL operations that are executed together. Either all
succeed or none (atomicity).
Steps:
1. Disable auto-commit
2. Execute multiple queries
3. Commit or rollback
Code:
con.setAutoCommit(false); // Start transaction
try {
Statement stmt = con.createStatement();
stmt.executeUpdate("UPDATE accounts SET balance = balance - 1000 WHERE id =
1");
stmt.executeUpdate("UPDATE accounts SET balance = balance + 1000 WHERE id =
2");
con.commit(); // If both succeed
System.out.println("Transaction Successful!");
} catch (SQLException e) {
con.rollback(); // If any fail
System.out.println("Transaction Rolled Back!");
}
(iv) Updatable ResultSet
Allows you to update, insert, or delete rows directly from the ResultSet.
Used with: ResultSet.CONCUR_UPDATABLE
Code:
Statement stmt = con.createStatement(
ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE);
ResultSet rs = stmt.executeQuery("SELECT * FROM students");
rs.absolute(1); // Go to first row
rs.updateString("name", "Nikhil Kumar");
rs.updateRow(); // Commit change to DB
// Inserting new row
rs.moveToInsertRow();
rs.updateInt("id", 105);
rs.updateString("name", "Nivi");
rs.insertRow();
(v) PreparedStatement
Used for executing parameterized SQL queries, which helps prevent SQL injection.
Faster and secure than Statement
Code:
String query = "INSERT INTO students (id, name) VALUES (1,”Nikhil”)";
PreparedStatement ps = con.prepareStatement(query);
ps.setInt(1, 110);
ps.setString(2, "Nivi");
ps.executeUpdate();
System.out.println("Inserted Successfully");
10. Explain transaction processing in JDBC. WAP to execute a Database connection.
(10M)
Sol.
Transaction processing is explained in the previous question.
Program-
(chatgpt provided code with reference to the pdf material)
11. List and explain exceptions occurred in JDBC.(5M)
Sol.
1. SQLException Description: This is the most commonly encountered exception in JDBC. It
occurs due to issues like:
Invalid SQL syntax
Connection failure
Missing tables or columns
Incorrect credentials
Useful Methods:
getMessage() – returns the error message.
getErrorCode() – returns vendor-specific error code.
Example:
try {
Statement stmt = con.createStatement();
stmt.executeQuery("SELECT * FROM non_existing_table");
} catch (SQLException e) {
System.out.println("Error: " + e.getMessage());
}
2. SQLWarning Description: SQLWarnings are less severe than exceptions. They indicate
minor issues like:
Deprecated features
Execution warnings by the driver or database
These do not stop program execution but should still be checked.
Useful Methods:
getWarning() – retrieves warnings on connections or statements.
getNextWarning() – gets the next warning in the chain.
Example:
SQLWarning warning = conn.getWarnings();
while (warning != null) {
System.out.println("Warning: " + warning.getMessage());
warning = warning.getNextWarning();
}
🔹 3. DataTruncation Description: Occurs when:
Data is truncated during insert or update (e.g., inserting a long string into a short
column)
Data exceeds the defined size of a column
**It is a subclass of **SQLWarning and may not throw an error but is important to check.
Example Scenario: Inserting a 20-character name into a VARCHAR(10) column may cause
DataTruncation.
12. List and elaborate Database Metadata object methods.(5M)
Sol.
DatabaseMetaData is an interface in JDBC used to retrieve detailed information (metadata)
about a database's structure, such as:
Tables
Columns
Primary keys
Schemas, etc.
You can access it using:
✅
DatabaseMetaData dbmd = connection.getMetaData();
**Common Methods of **DatabaseMetaData:
1. getDatabaseProductName()
Purpose: Returns the name of the database product.
Example Output: MySQL, Oracle, PostgreSQL
2. getUserName()
Purpose: Returns the username used for the database connection.
Example Output: "root" or any logged-in user
3. getURL()
Purpose: Returns the URL of the connected database.
Example: "jdbc:mysql://localhost:3306/mydb"
4. getSchemas()
Purpose: Returns the names of all schemas available in the database.
Helps identify database-level organization or structure.
5. getPrimaryKeys(String catalog, String schema, String table)
Purpose: Returns primary key information for the specified table.
Includes column names and sequence if composite keys exist.
6. getTables(String catalog, String schemaPattern, String tableNamePattern, String[] types)
Purpose: Returns metadata about tables in the database.
Can be filtered by table name or type (TABLE, VIEW, etc.).
13. Write a note on Metadata interface.(4M)
Sol.
\
package JDBCExample;
// 1. Import SQL package
import java.sql.*;
import java.util.Scanner;
public class JDBCDemoStudent {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/STUDENT"; // DB URL
String uname = "root"; // DB username
String pass = "password"; // DB password
Scanner sc = new Scanner(System.in);
try {
// 2. Load JDBC driver
Class.forName("com.mysql.cj.jdbc.Driver");
// 3. Connect to database
Connection con = DriverManager.getConnection(url, uname, pass);
// 4. Create statement
Statement st = con.createStatement();
// 5. Insert data
st.executeUpdate("INSERT INTO STUDENT VALUES (1, 'Amit', 20)");
st.executeUpdate("INSERT INTO STUDENT VALUES (2, 'Neha', 22)");
// 6. Update record
st.executeUpdate("UPDATE STUDENT SET AGE = 21 WHERE ID = 1");
// 7. Delete record
st.executeUpdate("DELETE FROM STUDENT WHERE ID = 2");
// 8. Search and display
ResultSet rs = st.executeQuery("SELECT * FROM STUDENT WHERE AGE > 18");
System.out.println("Student Details (Age > 18):");
System.out.println("---------------------------");
while (rs.next()) {
int id = rs.getInt("ID");
String name = rs.getString("NAME");
int age = rs.getInt("AGE");
System.out.println("ID: " + id);
System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("---------------------------");
}
// 9. Close resources
rs.close();
st.close();
con.close();
sc.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}