How To Create Connection To MySQL, PosgreSQL & Oracle Databases In Java Using JDBC

How To Create Connection To MySQL, PosgreSQL & Oracle Databases In Java Using JDBC

There are multiple ways to create database connection using JDBC API in java. But, here we are going to see most used and recommended ways to create database connection to MySQL, PostgreSQL & Oracle databases. There's just only five steps you need to follow for any database - 

  • Download vendor (MySQL, PostgreSQL & Oracle etc.) specefic driver jar from their website
  • Add that jar in your project's library/classpath
  • Load that driver in your application
  • Create connection-string / connection-url
  • Get connection using driver manager, connection-string, username and password

Create database connection to MySQL - 

Here's the code required to create connection to MySQL database. Before using it you need to download the MySQL connecter jar and add it to your project's library/classpath.

//Load MySQL JDBC Driver
Class.forName("com.mysql.jdbc.Driver");

//Create connection object
Connection connection = null;

//Get connection using Driver Manager
connection = DriverManager.getConnection("jdbc:mysql://hostname:port/dbname","username", "password");

//Close connection after database operations
connection.close();

Here's the full example on how to create MySQL database connection in java using JDBC - 

package com.codemeright.jdbc;

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

public class JDBCMySQLExample {

    public static void main(String... args) {

        Connection connection = null;

        String hostname = "localhost";
        String port = "3306";
        String databaseName = "testdb";
        String username = "root";
        String password = "password";
        String connectionString = "jdbc:mysql://" + hostname + ":" + port + "/" + databaseName;

        try {

            //Load MySQL JDBC Driver (Optional)
            Class.forName("com.mysql.jdbc.Driver");

            //Get connection using driver manager
            connection = DriverManager.getConnection(connectionString, username, password);
            if (connection != null) {
                System.out.println("Connection created successfully...");
            } else {
                System.out.println("Failed to create connection...");
                return;
            }

            //To do database operations like insert, update or delete etc.
            //Close connection after completion of database operations
            connection.close();

        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            try {
                if (connection != null) {
                    connection.close();
                }
            } catch (Exception e) {
            }
        }

    }
}

Create database connection to PostgreSQL - 

Here's the code required to create connection to PostgreSQL database. Before using it you need to download the PostgreSQL connecter jar and add it to your project's library/classpath. 

//Load PostgreSQL JDBC Driver
Class.forName("org.postgresql.Driver");

//Create connection object
Connection connection = null;

//Get connection using Driver Manager
connection = DriverManager.getConnection("jdbc:postgresql://hostname:port/dbname","username","password");

//Close connection after database operations
connection.close();

Here's the full example on how to create PostgreSQL database connection in java using JDBC -  

package com.codemeright.jdbc;

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

public class JDBCPostgreSQLExample {

    public static void main(String... args) {

        Connection connection = null;

        String hostname = "127.0.0.1";
        String port = "5432";
        String databaseName = "testdb";
        String username = "admin";
        String password = "admin@123";
        String connectionString = "jdbc:postgresql://" + hostname + ":" + port + "/" + databaseName;

        try {

            //Load PostgreSQL JDBC Driver (Optional)
            Class.forName("org.postgresql.Driver");

            //Get connection using driver manager
            connection = DriverManager.getConnection(connectionString, username, password);
            if (connection != null) {
                System.out.println("Connection created successfully...");
            } else {
                System.out.println("Failed to create connection...");
                return;
            }

            //To do database operations like insert, update or delete etc.
            //Close connection after completion of database operations
            connection.close();

        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            try {
                if (connection != null) {
                    connection.close();
                }
            } catch (Exception e) {
            }
        }

    }
}

Create database connection to Oracle - 

Here's the code required to create connection to Oracle database. Before using it you need to download the Oracle connecter jar and add it to your project's library/classpath.  

//Load Oracle JDBC Driver
Class.forName("oracle.jdbc.driver.OracleDriver");

//Create connection object
Connection connection = null;

//Get connection using Driver Manager
connection = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:SID","username","password");

//Close connection after database operations
connection.close();

Here's the full example on how to create Oracle database connection in java using JDBC -   

package com.codemeright.jdbc;

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

public class JDBCOracleExample {

    public static void main(String... args) {

        Connection connection = null;

        String hostname = "localhost";
        String port = "1521";
        String username = "system";
        String password = "password";
        String connectionString = "jdbc:oracle:thin:@//" + hostname + ":" + port + ":xe";

        try {

            //Load Oracle JDBC Driver (Optional)
            Class.forName("oracle.jdbc.driver.OracleDriver");

            //Get connection using driver manager
            connection = DriverManager.getConnection(connectionString, username, password);
            if (connection != null) {
                System.out.println("Connection created successfully...");
            } else {
                System.out.println("Failed to create connection...");
                return;
            }

            //To do database operations like insert, update or delete etc.
            //Close connection after completion of database operations
            connection.close();

        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            try {
                if (connection != null) {
                    connection.close();
                }
            } catch (Exception e) {
            }
        }

    }
}

As you can see in above examples, we've always closed our connections after completion of all database operations and also in finally block. That's because if any error occured during the execution of your sql query, the first connection close line will not get executed and your connection will remain open. That will create connection leackage problem in your application. So, it's the best practice to always close your connections in finally block. This way the connection will always get closed as the finally block is always gets executed even if there is any exception or no exception.

ADVERTISEMENT

About  |  Privacy Policy  |  Disclaimer  |  © Copyright 2018. All Rights Reserved.