Cant connect to my SQL database

2020-03-02 01:56发布

So I'm having an issue connecting to MySQL with Java. Heres my code:

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


public class DBAccess {
    private String Host;
    private String User;
    private String Password;

    public DBAccess() throws ClassNotFoundException, SQLException{
    Class.forName("com.mysql.jdbc.Driver");
    Password = "password";
    Host = "jdbc:mysql://localhost/worlddb";
    User = "root";
    @SuppressWarnings("unused")
    Connection connect = DriverManager.getConnection(Host,User,Password);
        System.out.println("Connected!"); 
    }
    public void RetreiveData(){

    }
    public void ChangeData(){
    }

}

The error that I'm getting is Exception in thread "main"

com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown database 'worlddb'

http://postimg.org/image/593stjvjx/ in mySQL workbench, my connection name is "worlddb" hostname is Liquidus(which is the localhost)

  • socket is MySQL
  • Port: 3306

Why is this?

标签: java mysql jdbc
9条回答
男人必须洒脱
2楼-- · 2020-03-02 02:28
connection = DriverManager.getConnection("jdbc:mysql://localhost/worlddb?" +"user=root&password=password");

Try this, I have a connection to mysql db with same connection, you just add ? after the name of the db.

查看更多
家丑人穷心不美
3楼-- · 2020-03-02 02:32

There is a difference between name of connection and name of Database,try world, test or sakila from schemas in the picture.

查看更多
三岁会撩人
4楼-- · 2020-03-02 02:32

In the above code, port number is missing.

connection = connection=DriverManager.getConnection("jdbc:mysql://localhost:3306/worlddb","root", "password");

default port number of mysql is 3306

查看更多
登录 后发表回答