JDBC Connections

Total Views : 235
Zoom In Zoom Out Read Later Print

In this post we will register driver and create a simple connection to MySQL server using JDBC.

Registering JDBC Driver
In order to create a connection to the database you need to register the driver for the database in your program, this driver depend on what type of database you are connecting to.

The most common way to register a driver is to use Java Class.forName() method. This method will load the driver's class file into memory, which registers it automatically.

App.java

import java.sql.*;

public class App {

    private static final String USER = "root";        // username
    private static final String PASS = "password123"; // password

    public static void main(String[] args) {
        Connection conn = null;
        try {
            // MySQL Database
            Class.forName("com.mysql.cj.jdbc.Driver");
            String DB_URL = "jdbc:mysql://localhost/test_db?useSSL=false";

            // PostgreSql Database
            //Class.forName("org.postgresql.Driver");
            //String DB_URL = "jdbc:postgresql://localhost/test_db?useSSL=false";

            // Oracle Database
            //Class.forName("oracle.jdbc.driver.OracleDriver");
            //String DB_URL = "jdbc:oracle:thin:@localhost:1521:test_db";

            // MS SQL Database
            //Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
            //String DB_URL = "jdbc:sqlserver://localhost:1433;databaseName=test_db;integratedSecurity=true;";

            conn = DriverManager.getConnection(DB_URL, USER, PASS);

            if (conn != null) {
                System.out.println("Connected....");

            } else {
                System.out.println("Failed to make connection!");
            }
        } catch (SQLException | ClassNotFoundException se) {
            se.printStackTrace();

        } finally {
            try {
                if (conn != null)
                    conn.close();
            } catch (SQLException se) {
                se.printStackTrace();
            }
        }
    }

}

Output:

13:14:09: Executing task 'App.main()'...

> Task :compileJava
> Task :processResources NO-SOURCE
> Task :classes

> Task :App.main()
Connected....

BUILD SUCCESSFUL in 1s
2 actionable tasks: 2 executed
13:14:11: Task execution finished 'App.main()'.

See More

Latest Photos