Wednesday, June 3, 2009

Accessing the Database using JDBC

import java.sql.*;

public class DBAccess {

public static void main(String args[]) {
  try {

     // Load the driver
     Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
  }catch (ClassNotFoundException e) {
     System.out.println("Unable to load        Driver Class");
     return;
   }

  try{
    // Create the Connection, Statement and the ResultSet
    Connection con = DriverManager.getConnection"jdbc:odbc:","","");
    Statement stmt = con.createStatement();
    ResultSet rs = stmt.executeQuery("Select * from Customers"); 
   
// Displaying Customer ID and Company Name from Customers table
    while (rs.next()) {
      System.out.println(rs.getString("CustomerID") + " " + rs.getString             ("CompanyName"));
    }
   // Closing the connections
    rs.close();
    stmt.close();
    con.close();
  }catch(SQLException e) {
     System.out.println(e.getMessage());
   }
  }
}

No comments:

Post a Comment