Connecting to a Database with a JDBC Connection object to obtain the connection - Java JDBC

Java examples for JDBC:Connection

Introduction

The following code demonstrates how to obtain a connection to an Oracle or Apache Derby database, depending on the specified driver.

Demo Code

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

public class Main {

  public Connection getConnection() throws SQLException {
    Connection conn = null;//from   w ww  .  j  ava  2  s. c  o m

    String hostname = null;
    String port = null;
    String database = null;
    String username = null;
    String password = null;
    String driver = null;
    String jndi = null;
    String jdbcUrl;
    if (driver.equals("derby")) {
      jdbcUrl = "jdbc:derby://" + hostname + ":" + port + "/" + database;
    } else {
      jdbcUrl = "jdbc:oracle:thin:@" + hostname + ":" + port + ":" + database;
    }
    conn = DriverManager.getConnection(jdbcUrl, username, password);
    System.out.println("Successfully connected");
    return conn;
  }
}

Related Tutorials