Connect to MYSQL (JDBC Example)
In this example I will show how to connect to mysql with JDBC driver. Let’s create the maven project with following pom.xml
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.java.jdbc</groupId> <artifactId>example</artifactId> <version>1.0-SNAPSHOT</version> <dependencies> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>6.0.5</version> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <configuration> <source>1.8</source> <target>1.8</target> <showDeprecation>true</showDeprecation> <showWarnings>true</showWarnings> <fork>true</fork> <encoding>UTF-8</encoding> </configuration> </plugin> </plugins> </build> </project> [addToAppearHere]
We need to add DatabaseConfiguration.java. Please note that in this example we use 6.0.5 version of the mysql driver and the new mysql JDBC driver class is:
com.mysql.cj.jdbc.Driver
following one is deprecated:
com.mysql.jdbc.Driver
public final class DatabaseConfiguration { /** * Mysql driver class name */ public static final String DRIVER_CLASS_NAME = "com.mysql.cj.jdbc.Driver"; /** * The URL */ public static final String URL = "jdbc:mysql://localhost:3306/techblog"; /** * The username */ public static final String USERNAME = "root"; /** * The password */ public static final String PASSWORD = "root"; private DatabaseConfiguration() { // no initialization } }
The next step will be to create the JDBCExample.java
package com.javajdbc.example; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import static com.javajdbc.example.DatabaseConfiguration.*; public class JDBCExample { public static void main(String[] argv) { final Connection connection = new JDBCExample().getConnection(); if (connection != null) { System.out.println("You are successfully created a connection..."); } else { System.out.println("Failed to create a connection..."); } } private Connection getConnection() { try { //Loading the driver class Class.forName(DRIVER_CLASS_NAME); } catch (ClassNotFoundException e) { System.out.println(e); } Connection connection = null; try { //Attempts to establish a connection connection = DriverManager.getConnection(URL, USERNAME, PASSWORD); } catch (SQLException e) { System.out.println(e); } return connection; } } [addToAppearHere]
And the last step of course we need to create the database with following script:
CREATE DATABASE techblog
DEFAULT CHARACTER SET utf8
DEFAULT COLLATE utf8_general_ci;
After the running JDBCExample.main method you should see following message.
You are successfully created a connection...