Josephine Josephine - 1 month ago 7
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;
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!!!

Answer

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();