Monday, March 28, 2011

Database Connctions in Java

// this example Works with MS Access. can be changed acc. any other database
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[])
      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( ) {
       System.out.println("Job  "+rs.getString("Job_Id"));
      rs.close(); //close resultset
      stmt.close(); // close statement
      con.close();  // close connection  
    catch(SQLException e)
    catch(ClassNotFoundException e)

No comments:

Post a Comment