JAVA N WEB TECH SYLLABUS

Wednesday, December 22, 2010

Displaying all the records from Student table

Here in this code we r displaying all the  student records from student table.In this example code we are makin use of jdbc driver type 4 provided by mysql.



import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
/*
 * Display.java
 *
 * Created on December 14, 2010, 9:25 AM
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */


/**
 *
 * @author Naveen
 */
public class Display2 {
    
    /** Creates a new instance of Display */
    public Display2() {
    }
    public static void main(String args[]) {
        
        Connection conn = null;
        ResultSet rs=null;
        Statement stmt = null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (ClassNotFoundException ex) {
            ex.printStackTrace();
        }
        String url="jdbc:mysql://localhost/studentinfo";
        String userName="root";
        String password="root";
        try {
            
            conn=DriverManager.getConnection(url,userName,password);
            
        }
        
        catch (SQLException ex) {
            System.out.println("Unable to Connect to Database");
        }
        
        try {
            
            String query="Select * from student" ;
            stmt=conn.createStatement();
            
            
            rs= stmt.executeQuery(query);
            while(rs.next()) {
                System.out.print(rs.getString("usn")+"\t");
                System.out.print(rs.getString(2)+"\t");
                System.out.print(rs.getString(3)+"\t");
                
                System.out.print(rs.getInt(4)+"\t");
                System.out.println(rs.getFloat(5)+"\t");
            }
            
            
            
            
        } catch (SQLException ex) {
            System.out.println("Unable to create Statment");
        }
        
        
        
        
        
    }
}

No comments:

Post a Comment