Connecting to a MySQL Database - Java JDBC

Java examples for JDBC:MySQL

Description

Connecting to a MySQL Database

mysql> GRANT ALL PRIVILEGES ON *.* TO username@localhost

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

public class Main {
  public static void main(String[] argv) throws Exception {
    Connection connection = null;
    try {
      // Load the JDBC driver
      String driverName = "org.gjt.mm.mysql.Driver"; // MySQL MM JDBC driver
      Class.forName(driverName);

      // Create a connection to the database
      String serverName = "localhost";
      String mydatabase = "mydatabase";
      String url = "jdbc:mysql://" + serverName + "/" + mydatabase; // a JDBC
                                                                    // url
      String username = "username";
      String password = "password";
      connection = DriverManager.getConnection(url, username, password);
    } catch (ClassNotFoundException e) {
      // Could not find the database driver
    } catch (SQLException e) {
      // Could not connect to the database
    }
  }
}

Related Tutorials