Skip to main content

APIzation: Replication Package

[Q#4436146][A#4436173] How to connect to local host using JDBC?

https://stackoverflow.com/q/4436146

I installed MySql on my own machine. I created database, create table, … using MySql CommandLine Client. When working on a project in school, I connected to school's database using this syntax: In my local machine, I don't have to type in user name, all I did is just login with my password as root user: I would like to know how can I connect to my local machine's database? what should I put as parameters within method .getConnection Best regards, Chan

Answer

https://stackoverflow.com/a/4436173

Simple Connection:

APIzation

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

public class Main {
  public static void main(String[] argv) throws Exception {
    String driverName = "org.gjt.mm.mysql.Driver";
    Class.forName(driverName);

    String serverName = "localhost";
    String mydatabase = "mydatabase";
    String url = "jdbc:mysql://" + serverName + "/" + mydatabase; 

    String username = "username";
    String password = "password";
    Connection connection = DriverManager.getConnection(url, username, password);
  }
}
package com.stackoverflow.api;

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

public class Human4436173 {

  public static Connection initConnection() throws Exception {
    String driverName = "org.gjt.mm.mysql.Driver";
    Class.forName(driverName);

    String serverName = "localhost";
    String mydatabase = "mydatabase";
    String url = "jdbc:mysql://" + serverName + "/" + mydatabase;

    String username = "username";
    String password = "password";
    return DriverManager.getConnection(url, username, password);
  }
}

package com.stackoverflow.api;

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

/**
 * How to connect to local host using JDBC?
 *
 * @author APIzator
 * @see <a href="https://stackoverflow.com/a/4436173">https://stackoverflow.com/a/4436173</a>
 */
public class APIzator4436173 {

  public static Connection connect(
    String driverName,
    String serverName,
    String mydatabase,
    String username,
    String password
  ) throws Exception {
    Class.forName(driverName);
    String url = "jdbc:mysql://" + serverName + "/" + mydatabase;
    return DriverManager.getConnection(url, username, password);
  }
}