Tuesday, September 9, 2025

MCA 1 : Introduction to JDBC Program for IT Students

 Prepared By :Prof.  Uday Shah (HOD-IT)

 MCA 1 : Introduction to JDBC Program 

1. JDBC Architecture and Drivers

  • JDBC (Java Database Connectivity) is a Java API that allows Java programs to interact with relational databases.
  • It provides a set of interfaces and classes under java.sql and javax.sql packages.
  • JDBC follows a layered architecture:
  • Application → JDBC API → JDBC Driver Manager → JDBC Driver → Database
  • JDBC API: Defines interfaces such as Connection, Statement, PreparedStatement, ResultSet, etc.
  • Driver Manager: Manages the list of database drivers. It matches connection requests with the proper driver.
  • JDBC Driver: A software component that translates JDBC calls into database-specific calls.
  • Types of JDBC Drivers:
    1. Type 1: JDBC-ODBC Bridge Driver – uses ODBC, platform-dependent.
    2. Type 2: Native API Driver – uses native DB client libraries.
    3. Type 3: Network Protocol Driver – communicates with middleware servers.
    4. Type 4: Thin Driver – Pure Java, directly connects to DB (most widely used).
  • Example:
  • Class.forName("com.mysql.cj.jdbc.Driver"); // Load MySQL Driver
  • This architecture ensures platform independence and flexibility.

 

2. Establishing a Database Connection

  • After loading the driver, the next step is to establish a connection.
  • A connection represents a session between the Java app and the database.
  • We use DriverManager.getConnection() method.
  • Syntax:
  • Connection con = DriverManager.getConnection(
  •     "jdbc:mysql://localhost:3306/studentdb", "root", "password");
  • Here:
    • "jdbc:mysql://localhost:3306/studentdb" → Database URL
    • "root" → Username
    • "password" → Password
  • Once connected, we can execute SQL queries.
  • If the connection fails, JDBC throws a SQLException.
  • A connection must always be closed using con.close() to free resources.
  • Multiple connections can be created to interact with different databases.
  • Example check:
  • if (con != null) System.out.println("Connected Successfully!");

 

3. Creating a SQL Query

  • SQL queries are written as strings in Java.
  • Example:
  • String query = "INSERT INTO student(rollno, name) VALUES (1, 'Amit')";
  • SQL queries are of different types:
    • DDL (Data Definition Language): CREATE, DROP, ALTER
    • DML (Data Manipulation Language): INSERT, UPDATE, DELETE
    • DQL (Data Query Language): SELECT
  • Queries can be static or parameterized.
  • Static queries are used with Statement.
  • Parameterized queries (with ?) are used with PreparedStatement.
  • Example of UPDATE query:
  • String update = "UPDATE student SET name='Ravi' WHERE rollno=1";
  • Queries must follow the database’s SQL syntax.
  • Improper queries cause SQLException.

 

4. Executing SQL Queries using Statement

  • The Statement object is used to execute static SQL queries.
  • Created using:
  • Statement stmt = con.createStatement();
  • It provides 3 main methods:
    • executeQuery(sql) → Executes SELECT, returns ResultSet.
    • executeUpdate(sql) → Executes INSERT/UPDATE/DELETE, returns int (affected rows).
    • execute(sql) → Executes any query, returns boolean.
  • Example:
  • ResultSet rs = stmt.executeQuery("SELECT * FROM student");
  • while(rs.next()) {
  •     System.out.println(rs.getInt("rollno")+" "+rs.getString("name"));
  • }
  • Limitation: Cannot handle dynamic values efficiently.
  • Security risk: SQL Injection (malicious SQL through user input).

 

5. Executing SQL Queries using PreparedStatement

  • PreparedStatement is used for dynamic/parameterized queries.
  • Benefits:
    1. Prevents SQL injection.
    2. Reusable for multiple executions.
    3. Faster than Statement (precompiled).
  • Example:
  • PreparedStatement ps = con.prepareStatement(
  •     "INSERT INTO student VALUES(?, ?)");
  • ps.setInt(1, 2);
  • ps.setString(2, "Sita");
  • ps.executeUpdate();
  • Supports different data types: setInt(), setString(), setDouble(), etc.
  • Example (Update):
  • ps = con.prepareStatement("UPDATE student SET name=? WHERE rollno=?");
  • ps.setString(1, "Rahul");
  • ps.setInt(2, 2);
  • ps.executeUpdate();

 

6. Executing SQL Queries using CallableStatement

  • CallableStatement is used to call stored procedures in DB.
  • A stored procedure is a precompiled group of SQL statements stored in the database.
  • Syntax:
  • CallableStatement cs = con.prepareCall("{call getStudent(?)}");
  • cs.setInt(1, 1);
  • ResultSet rs = cs.executeQuery();
  • Example Stored Procedure in MySQL:
  • CREATE PROCEDURE getStudent(IN roll INT)
  • BEGIN
  •   SELECT * FROM student WHERE rollno = roll;
  • END;
  • Advantages:
    1. Faster (precompiled on DB side).
    2. Useful for business logic inside DB.
    3. Supports IN, OUT, INOUT parameters.

 

7. ResultSet

  • The ResultSet object holds query results (like a virtual table).
  • Obtained from executeQuery().
  • Cursor starts before the first row.
  • Common methods:
    • next() → Moves to next row.
    • getInt(colName) → Returns integer value.
    • getString(colName) → Returns string value.
    • first(), last(), previous(), absolute(n).
  • Example:
  • ResultSet rs = stmt.executeQuery("SELECT * FROM student");
  • while(rs.next()) {
  •     System.out.println(rs.getInt(1)+" "+rs.getString(2));
  • }
  • Types of ResultSet:

1.                  TYPE_FORWARD_ONLY (default).

2.                  TYPE_SCROLL_INSENSITIVE (can move both ways, no changes reflected).

3.                  TYPE_SCROLL_SENSITIVE (changes in DB are reflected).

 

8. ResultSetMetaData

  • Provides information about ResultSet columns.
  • Useful when we don’t know table structure.
  • Example:
  • ResultSetMetaData rsmd = rs.getMetaData();
  • int cols = rsmd.getColumnCount();
  • for(int i=1; i<=cols; i++) {
  •     System.out.println(rsmd.getColumnName(i)+" - "+rsmd.getColumnTypeName(i));
  • }
  • Returns details like:
    • Column count
    • Column names
    • Data type of each column
    • Column size
  • Example output:
  • rollno - INT 
  • name - VARCHAR
  • Helps in dynamic applications (like displaying data without hardcoding column names).

 

9. Handling Exceptions in JDBC

  • JDBC operations may throw SQLException.
  • Always handle using try-catch-finally.
  • Example:
  • try {
  •     Connection con = DriverManager.getConnection(...);
  • } catch(SQLException e) {
  •     System.out.println("Error: " + e.getMessage());
  • } finally {
  •     con.close();
  • }
  • SQLException provides details:
    • getMessage() → Error message
    • getSQLState() → SQL error code
    • getErrorCode() → Vendor-specific error code
  • Use finally block to close resources (Connection, Statement, ResultSet).
  • Java 7 introduced try-with-resources for auto-closing.

 

10. Transactions in JDBC

  • A transaction is a group of SQL statements executed as one unit.
  • By default, JDBC uses auto-commit mode (each query is committed instantly).
  • To use transactions:
  • con.setAutoCommit(false);
  • stmt.executeUpdate("INSERT INTO student VALUES(5, 'Rohan')");
  • stmt.executeUpdate("UPDATE student SET name='Mohan' WHERE rollno=5");
  • con.commit(); // both succeed together
  • If any query fails:
  • con.rollback(); // undo changes
  • Ensures ACID properties (Atomicity, Consistency, Isolation, Durability).
  • Used in banking systems, booking systems, e-commerce.

 

11. Savepoints in JDBC

  • Savepoints are checkpoints inside a transaction.
  • Allows rolling back to a specific point without undoing the entire transaction.
  • Example:
  • con.setAutoCommit(false);
  • Savepoint sp1 = con.setSavepoint("step1");
  • stmt.executeUpdate("INSERT INTO student VALUES(6, 'Anita')");
  • Savepoint sp2 = con.setSavepoint("step2");
  • stmt.executeUpdate("INSERT INTO student VALUES(7, 'Karan')");
  • con.rollback(sp2); // rollback only Karan
  • con.commit();
  • Benefits:
    • Greater control in complex transactions.
    • Allows partial rollbacks.
  • Used in systems where multiple operations happen in one transaction.

 

 


BCA 1 - Working with Arrays and Structures in C for IT Students

 Prepared By : Prof. Uday Shah (HOD-IT)

I.M.C.A Semester – 1

C Language

Unit – 4

 


Unit -4: C Working with Arrays

Contents

1. Introduction About an Array. 3

2. Declaration and Initialization of an Array. 3

3. Accessing Array Elements. 4

4. Types of Arrays. 4

5. Array with Functions Using UDF. 5

6. Introduction to Structure. 5

7. Declaration and Initialization of Structure. 6

8. Nested Structure. 6

9. Array within Structure. 7

10. Array of Structure. 8

11. Passing Structure to UDF. 8

 

Working with Arrays and Structures in C


1. Introduction About an Array

  • An array is a collection of elements of the same data type stored in contiguous memory locations.
  • It allows storing multiple values under a single variable name.
  • Each element is accessed using an index, starting from 0.
  • Arrays simplify program design by reducing the need for multiple variables.
  • Example: Instead of using int a1, a2, a3…, we use int arr[10];.
  • Arrays can store integers, floats, characters, or even structures.
  • Arrays provide sequential access making them efficient for iteration.
  • They are static in size, meaning once declared, the size cannot be changed.
  • Useful in scenarios like storing marks of students, salaries, etc.
  • Example:
  • int marks[5] = {90, 85, 78, 88, 95};
  • Here, marks[0] = 90 and marks[4] = 95.
  • Declaration tells the compiler the type and size of the array.
  • Syntax: datatype arrayName[size];.
  • Initialization assigns values at the time of declaration.
  • Example: int arr[5] = {10,20,30,40,50};.
  • If not fully initialized, remaining elements are set to 0.
  • Example: int arr[5] = {1,2}; // rest = 0.
  • Array elements can also be initialized individually after declaration.
  • Example:
  • int arr[3];
  • arr[0] = 10; arr[1] = 20; arr[2] = 30;
  • Array size must be known at compile time (unless using dynamic memory).
  • Provides structured storage for multiple values.
  • Used in data management, searching, sorting, etc.

 

  • Array elements are accessed using index numbers.
  • Index starts from 0 (first element).
  • Example: arr[0] refers to the first element, arr[n-1] refers to the last.
  • Elements can be read/written inside loops.
  • Example:
  • for(int i=0; i<5; i++)
  •     printf("%d ", arr[i]);
  • Elements can be updated: arr[2] = 50;.
  • Accessing outside the range (out of bounds) leads to undefined behavior.
  • Array indexing provides random access → direct access to any element.
  • Useful in searching, sorting, and mathematical operations.
  • Accessing is O(1) operation (constant time).

Arrays are classified into different types:

(a) One Dimensional Array

  • A list of elements in a single row/line.
  • Example: int arr[5] = {1,2,3,4,5};.
  • Accessed using a single index.
  • Useful for storing linear data (marks, ages, etc.).

(b) Two Dimensional Array

  • Represents data in rows and columns (matrix form).
  • Declared as: int arr[3][3];.
  • Example:
  • int matrix[2][2] = {{1,2}, {3,4}};
  • Accessed using two indexes: matrix[0][1].

(c) Multi Dimensional Array

  • Arrays with 3 or more dimensions.
  • Used in mathematical models, 3D graphics, etc.
  • Example: int arr[3][3][3];.

(d) Character Array (String)

  • A collection of characters stored in sequence.
  • Ends with \0 (null character).
  • Example: char name[10] = "Hello";.
  • Strings are widely used in text processing.
  • Arrays can be passed to functions for processing.
  • Since arrays are passed by reference, functions can modify original values.
  • Example:
  • void display(int arr[], int n) {
  •     for(int i=0; i<n; i++) printf("%d ", arr[i]);
  • }
  • int main() {
  •     int a[5] = {1,2,3,4,5};
  •     display(a,5);
  • }
  • Functions make array operations modular and reusable.
  • Common operations: sum, average, search, sort.
  • Passing arrays helps in handling large data efficiently.
  • Useful in modular programming with clean code.
  • Advantage: Reduces redundancy in code.
  • A structure is a user-defined data type in C.
  • It groups different types of variables under a single name.
  • Example: A student has id, name, marks, which can be grouped in a structure.
  • Declared using the struct keyword.
  • Example:
  • struct Student {
  •     int id;
  •     char name[20];
  •     float marks;
  • };
  • Structures improve data organization.
  • Unlike arrays, they can store heterogeneous data types.
  • Widely used in real-world applications like databases.
  • They support nested structures, arrays inside structures, etc.
  • Declared using struct keyword followed by members.
  • Example:
  • struct Student {
  •     int id;
  •     char name[20];
  • };
  • Structure variables can be declared in two ways:
    1. Along with structure definition.
    2. Separately in main().
  • Initialization:
  • struct Student s1 = {101, "Raj"};
  • Access members using the dot (.) operator: s1.id, s1.name.
  • Default values are not assigned; must be initialized.
  • Allows structured storage of multiple attributes.
  • Makes handling related data easier.
  • A structure inside another structure is called nested structure.
  • Helps in organizing hierarchical data.
  • Example:
  • struct Address {
  •     char city[20];
  •     int pincode;
  • };
  • struct Student {
  •     int id;
  •     char name[20];
  •     struct Address addr;
  • };
  • Access: s1.addr.city.
  • Useful in real applications like storing employee info with addresses.
  • Increases flexibility of structures.
  • Can combine multiple small structures into a bigger one.
  • Reduces complexity in database-like programs.
  • Used in complex data modeling.
  • Structures can hold arrays as members.
  • Example:
  • struct Student {
  •     int id;
  •     char name[20];
  •     int marks[5]; // array inside structure
  • };
  • Useful for storing multiple values related to one entity.
  • Example: storing 5 subjects’ marks of one student.
  • Access: s1.marks[0].
  • Provides structured storage of grouped array data.
  • Improves program organization.
  • Useful in real-world tasks like storing transaction details.
  • A collection of multiple structure variables stored in an array.
  • Example:
  • struct Student {
  •     int id;
  •     char name[20];
  • } s[3];
  • Stores multiple students’ records in a single array.
  • Access: s[0].id, s[1].name.
  • Very useful for handling large datasets like employee or student records.
  • Combines both arrays and structures.
  • Reduces memory waste by storing multiple objects systematically.
  • Helps in building databases in C.
  • Extensively used in practical applications.
  • Structures can be passed to functions by value or reference.
  • By value: A copy of structure is passed, original remains unchanged.
  • By reference: Address is passed, changes affect original structure.
  • Example:
  • void display(struct Student s) {
  •     printf("%d %s", s.id, s.name);
  • }
  • Calling: display(s1);.
  • Useful for modular programming.
  • Functions can process student, employee, or product records.
  • Helps in organizing large applications.
  • Efficient way to pass and manipulate real-world data.

   

Thank You

:: Any Query ::

Contact: Ruparel Education Pvt. Ltd.

Mobile No: 7600044051