Advanced Java Programming Practical 19

Question 1
Develop JDBC program to retrieve data using ResultSet
ResultDemo.java
Java
				import java.sql.*;

public class ResultDemo
{
    public static void main(String args[])
    {
        try
        {
            Class.forName("com.mysql.jdbc.Driver");
            System.out.println("Driver loaded");
            Connection con= DriverManager.getConnection("jdbc:mysql://localhost:3306/javadb1","root","");
            System.out.println("Connection to the database created");
            Statement st = con.createStatement();
            String query = "select * from employee";
            ResultSet rs=st.executeQuery(query);
            System.out.println("Employee Id\t\t\tEmployee Name");
            while(rs.next())
            {
                System.out.println(rs.getInt(1)+"\t\t\t"+rs.getString(2));
            }
        }
        catch (SQLException e)
        {
            System.out.println(e);
        }
        catch (ClassNotFoundException e)
        {
            throw new RuntimeException(e);
        }
    }
}

			
Output
Question 2
Develop a program to update a record in database table
UpdateDemo.java
Java
				import java.sql.*;
public class UpdateDemo
{
    public static void main(String args[])
    {
        try
        {
            Class.forName("com.mysql.jdbc.Driver");
            System.out.println("Driver loaded");
            Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/javadb1", "root", "");
            System.out.println("Connection to the database created");
            PreparedStatement pstmt = con.prepareStatement("update student set sclass='CM4I' where sclass=?");
            pstmt.setString(1,"CM3I");
            int i=pstmt.executeUpdate();
            System.out.println(i+" records updated");
            con.close();
        }
        catch (SQLException e)
        {
            System.out.println(e);
        }
        catch (ClassNotFoundException e)
        {
            System.out.println(e);
        }
    }
}
			
Output

Leave a Comment

Your email address will not be published. Required fields are marked *