Saturday, 18 April 2015

Procedure For Database Connectivity (JDBC)

JDBC Connection Consists of 6 Steps -
  •   Loading the driver
  •   Establish the connection
  •   Create a Statement object
  •   Execute the query using Statement Object
  •   Close the connection


here is the simple code for JDBC connection -


Here i am using postgresql as a database and you can use any different database which you like to use :





 import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.SQLException;

public class JDBCExample {

  public static void main(String args[]) {

 System.out.println("-------- postgreSQL JDBC Connection Testing ------------");

 try {
  Class.forName("org.postgresql.Driver");
 } catch (ClassNotFoundException e) {
  System.out.println("Where is your postgreSQL JDBC Driver?");                         
  System.out.println("Failed to load Driver !");
  e.printStackTrace();
  return;
 }

 System.out.println("postgreSQL JDBC Driver Registered!");
 Connection connection = null;

 try {
  connection = DriverManager
  .getConnection("jdbc:postgresql://localhost:5432/postgres", "postgres", "p@ssw0rd");

 } catch (SQLException e) {
  System.out.println("Connection Failed! Check output console");
  e.printStackTrace();
  return;
 }

 if (connection != null) {
  System.out.println("You made it, take control your database now!");
 } else {
  System.out.println("Failed to make connection!");
 }
  }

No comments:

Post a Comment