How To Connect to MySQL with a JDBC Driver
This example will show you how to connect to MySQL database via a JDBC driver.
First, download the MySQL JDBC Driver.
This will show you how to open a database connection.
To run this code, your need mysql-connector-java-{version}-bin.jar in your classpath.
JDBCMySQLExample.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 |
package com.vertex.academy.databases; //STEP 1. Import required packages import java.sql.DriverManager; import java.sql.Connection; import java.sql.SQLException; public class JDBCMySQLExample { // Database credentials static final String DB_URL = "jdbc:mysql://localhost:3306/vertex" static final String USER = "username"; static final String PASS = "password"; public static void main(String[] argv) { System.out.println("Testing connection to MySQL JDBC"); try { Class.forName("com.mysql.jdbc.Driver"); } catch (ClassNotFoundException e) { System.out.println("MySQL JDBC Driver is not found"); e.printStackTrace(); return; } System.out.println("MySQL JDBC Driver connected"); Connection connection = null; try { connection = DriverManager .getConnection(DB_URL, USER, PASS); } catch (SQLException e) { System.out.println("Connection Failed"); e.printStackTrace(); return; } if (connection != null) { System.out.println("You connected to database now"); } else { System.out.println("Failed to make connection to database"); } } } |
To run the code, put JDBCExample.java in the same folder as the MySQL JDBC driver (for example c:\test) and execute:
C:\test>java -cp c:\test\mysql-connector-java-5.1.8-bin.jar;c:\test JDBCExample
You should see:
1 2 3 |
Testing connection to MySQL JDBC MySQL JDBC Driver connected You connected to database now |