This blog is about providing theory as well as simple executable codes of different programming languages such as java, C, C++, and web programming, etc. This blog will be helpful to the IT students to learn about programming.

Wednesday, March 8, 2023

What are JDBC and ODBC? Write a java program using JDBC to extract name of those students who live in Morang district, assuming that student table has four attributes (ID, name, district, and age).

 JDBC (Java Database Connectivity) and ODBC (Open Database Connectivity) are application programming interfaces (APIs) that allow Java and other programming languages to interact with databases.

Here's an example Java program that uses JDBC to extract the names of students who live in Morang district, assuming that the student table has four attributes (ID, name, district, and age):

import java.sql.*;

public class StudentList {
    public static void main(String[] args) {
        try {
            // load the JDBC driver
            Class.forName("com.mysql.jdbc.Driver");

            // create a connection to the database
            Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb", "username", "password");

            // create a statement object
            Statement stmt = conn.createStatement();

            // execute the SQL query
            ResultSet rs = stmt.executeQuery("SELECT name FROM student WHERE district='Morang'");

            // iterate through the result set and print the names of the students
            while (rs.next()) {
                String name = rs.getString("name");
                System.out.println(name);
            }

            // close the resources
            rs.close();
            stmt.close();
            conn.close();
        } catch (Exception e) {
            System.err.println("Exception: " + e.getMessage());
        }
    }
}

This program loads the JDBC driver, creates a connection to the database, creates a statement object, and executes an SQL query to select the names of the students who live in Morang district. The program then iterates through the result set and prints the names of the students. Finally, the program closes the resources (result set, statement, and connection).

Note that you will need to replace the jdbc:mysql://localhost:3306/mydb URL with the URL of your own database, and replace the username and password with your own database credentials. Also, you will need to include the JDBC driver JAR file in your classpath.

No comments:

Post a Comment

If you have any doubts, please let me know

Slider Widget