Advanced Java Programming - Old Questions

Question Answer Details

3. Write a Java program using JDBC to extract name of those students who live in Kathmandu district, assuming that the student table has four attributes (ID, name, district, and age).

10 marks
Asked in 2072

Answer

AI Generated Answer

AI is thinking...

Official Answer

Before Writing the code please run the Xampp server and create a database name test and add a table called student with (id, name, district and age) column name.

Program

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.ResultSet;

import java.sql.SQLException;

import java.sql.Statement;

public class Studentjdbc{

public static void main( String args[] ) {

try{

          //Load the JDBC driver

            Class.forName("com.mysql.jdbc.Driver");

           // Establish a connection

            String url = "jdbc:mysql//localhost/test";

            String username = "root";

            String password = "";

            Connection conn = DriverManager.getConnection(url, username, password);

           //Create a statement

            Statement st = conn.createStatement();

           //Execute a statement

            ResultSet rs = st.executeQuery("SELECT name FROM student WHERE district = 'Katmandu' ");

            while(rs.next()){

String name = rs.getString("name");

System.out.println("Name: "+ name);

}

            st.close();

            conn.close();

    }catch (SQLException sqlExcep){

System.out.println("Error: " + sqlExcep.getMessage());

}

      }

}