Sandeep Bansal
Sandeep Bansal

Reputation: 6394

How to make a MySQL Connection in JAVA

I can't seem to get a connection made on my Java program to java, I have started the MySQL Server, made a database in phpMyAdmin. But I'm confused on how I should use the JDBC Driver that I downloaded from MySQL.

Here's my code:

    private void startConnection()
{
Connection conn = null;
String url = "jdbc:mysql://localhost/";
String dbName = "bank";
String driver = "com.mysql.jdbc.Driver";
String userName = "root";
String password = "password";
try {
  Class.forName(driver).newInstance();
  conn = DriverManager.getConnection(url+dbName,userName,password);
  System.out.println("Connected to the database");
  conn.close();
  System.out.println("Disconnected from database");
} catch (Exception e) {
    System.out.println("NO CONNECTION =(");
}
}

I had included the jar file in my JDK - jre\lib\ext folder but nothing. Any ideas?

Thanks in advance.

Upvotes: 2

Views: 20775

Answers (3)

CodeMadness
CodeMadness

Reputation: 1

private void startConnection()
{
    Connection conn = null;
    String url = "jdbc:mysql://localhost:3306/";
    String dbName = "bank";
    String driver = "com.mysql.jdbc.Driver";
    String userName = "root";
    String password = "password";

    try
    {
        Class.forName(driver).newInstance();
        conn = DriverManager.getConnection(url+dbName,userName,password);
        System.out.println("Connected to the database");
        conn.close();
        System.out.println("Disconnected from database");

    }
    catch (Exception e)
    {
        System.out.println("NO CONNECTION =(");
    }
}

This will work

Upvotes: 0

Alexis Dufrenoy
Alexis Dufrenoy

Reputation: 11946

You have to specify the port. It's String url = "jdbc:mysql://localhost:3306/"; by default.

Upvotes: 1

corriganjc
corriganjc

Reputation: 690

One thing stands out: you haven't specified a network port in the URL. The default port is 3306. So try:

jdbc:mysql://localhost:3306/

For the URL.

Upvotes: 3

Related Questions