Josephine
Josephine

Reputation: 77

Not able to connect to MySQL using Java

I am using the below code to connect to MySQL

import java.sql.DriverManager;
import com.mysql.jdbc.Connection;


public class connectMysql {
    public static void main(String[] args){
        Connection conn = null;
        try{
            conn = (Connection)DriverManager.getConnection("jdbc:mysql://localhost:3306//test","root","admin");
            if(conn!=null)
            {
                System.out.println("Connected successfully");
            }
        }catch(Exception e)
        {
            System.out.println("Not connected");
            e.printStackTrace();
        }
    }
}

The username: root, password: admin, Hostname: localhost, Port: 3306. I get the output as "Not connected".

[Edits] Now I Stack Trace and see that error is 'Unknown database '/test'. But I do have a schema named test. Is the schema same as the database?

Everything is same as this. But I don't seem to get connected to the DB. Thanks for the help!!!

Upvotes: 0

Views: 1072

Answers (2)

Parthasarathy
Parthasarathy

Reputation: 318

Check all the drivers are available in the Library

Check for the port number, Username and password(case Sensitive)

if every thing is correct then

use the below code

Class.forName("com.mysql.jdbc.Driver");
  // Setup the connection with the DB
  con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "username", "password"); 
  statement = con.createStatement();

Upvotes: 1

mhasan
mhasan

Reputation: 3709

Why you have double slash // before your database name in your connection string

jdbc:mysql://localhost:3306//test","root","admin"

Change it to

jdbc:mysql://localhost:3306/test","root","admin"

Upvotes: 2

Related Questions