skip to main | skip to sidebar

Java Programs and Examples with Output

Pages

▼
 
  • RSS
  • Twitter
Monday, October 15, 2012

How to retrieve Datas from Database using Java Program

Posted by Raju Gupta at 10:00 PM – 0 comments
 
Initially connection is made for the Database and Query is written for retrieving the Datas.

import java.sql.*;

public class RetriveAllEmployees{
 public static void main(String[] args) { 
   System.out.println("Getting All Rows from employee table!"); 
   Connection con = null;  
   String url = "jdbc:mysql://localhost:3306/";  
   String db = "jdbc"; 
   String driver = "com.mysql.jdbc.Driver";  
   String user = "root"; 
   String pass = "root";
   
   try{
    Class.forName(driver); 
    con = DriverManager.getConnection(url+db, user, pass);
   
    Statement st = con.createStatement(); 
    ResultSet res = st.executeQuery("SELECT * FROM  employee");  
   
    System.out.println("Employee Name: " );
     
    while (res.next()) { 
      String employeeName = res.getString("employee_name"); 
      System.out.println(employeeName );  
    } 
    con.close();
   } catch (ClassNotFoundException e) {  
    System.err.println("Could not load JDBC driver");
    System.out.println("Exception: " + e); 
    e.printStackTrace();  
    } catch(SQLException ex) { 
     System.err.println("SQLException information");  
   
     while(ex!=null) { 
      System.err.println ("Error msg: " + ex.getMessage()); 
      System.err.println ("SQLSTATE: " + ex.getSQLState());
      System.err.println ("Error code: " + ex.getErrorCode()); 
      ex.printStackTrace();  ex = ex.getNextException(); // For drivers that support chained exceptions  
     }
    }  
   }
} 




Labels: Java Database Example , JDBC

Leave a Reply

Newer Post Older Post
Subscribe to: Post Comments ( Atom )
  • Popular
  • Recent
  • Archives
Powered by Blogger.
 
 
 
© 2011 Java Programs and Examples with Output | Designs by Web2feel & Fab Themes

Bloggerized by DheTemplate.com - Main Blogger