Monday, March 28, 2011

Database Connctions in Java

This example Works with MS Access to explain DB concepts and can be changed accordingly to any other database for that you will need to configure their respective JAR libraries to your project i.e. for MY-SQL you will need MySQL-Connector JAR
       
import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.ResultSet;

import java.sql.SQLException;

import java.sql.Statement;

public class dbConnections

{

public static void main(String args[])

{

     try{  

      Class.forName("sun.jdbc.odbc.JdbcOdbc");  //load DB drivers

      Connection con=DriverManager.getConnection("jdbc:odbc:DBName",username,pwd);

      //create db connections

      Statement stmt = con.createStatement(); // creates statement for db access

      String query = "SELECT * FROM Job"; // sql query

      ResultSet rs = stmt.executeQuery(query);

      //execute sql query and stores the result in the result set rs

      while( rs.next() ) {

       System.out.println("Job  "+rs.getString("Job_Id"));

      }

      rs.close(); //close resultset

      stmt.close(); // close statement 

      con.close();  // close connection   

     }

    catch(SQLException e)

    {

     System.out.println(e);

    }

    catch(ClassNotFoundException e)

    {

     System.out.println(e);

   }

}

}

No comments:

Post a Comment