Josephine Josephine - 1 year ago 85
Java Question

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;
conn = (Connection)DriverManager.getConnection("jdbc:mysql://localhost:3306//test","root","admin");
System.out.println("Connected successfully");
}catch(Exception e)
System.out.println("Not connected");

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!!!

Answer Source

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

  // Setup the connection with the DB
  con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "username", "password"); 
  statement = con.createStatement();
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download