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:09

Make sure that the database what you have mentioned in Host = "jdbc:mysql://localhost/worlddb"; i.e worlddb is correct or not. The name of the database here is CASE SENSITIVE! So, if you try to connect using a database name like "test2" instead of "Test2" , you will get the

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

Also try using port number too

Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/worlddb", "root", "password");
查看更多
趁早两清
3楼-- · 2020-03-02 02:11

Take care to not have white spaces and use jdbc:mysql://localhost:3306/dbname

查看更多
疯言疯语
4楼-- · 2020-03-02 02:18

Are you sure that the DB server is not case sensitive? I mean maybe on the DB server the DB name is WorldDb and you are trying to connect to it by using worlddb (all low lecters).. Try to use the same name or to configure MySQL to be case insensitive

查看更多
爱情/是我丢掉的垃圾
5楼-- · 2020-03-02 02:18

Charaf jra was right i had the same issue.
your schema(schema = Database) is listed as Host = "jdbc:mysql://localhost/worlddb"; If you look at the schemas in the pic you posted https://postimg.cc/image/593stjvjx/
the schema(Database) is world.

查看更多
仙女界的扛把子
6楼-- · 2020-03-02 02:19

Try this it's hopeful for you:

Connection con = null;
Class.forName("com.mysql.jdbc.Driver");
con =DriverManager.getConnection("jdbc:mysql://localhost/worlddb","root","password"); 
查看更多
Fickle 薄情
7楼-- · 2020-03-02 02:22

Write

"jdbc:mysql://localhost:3306/worlddb"

instead of

"jdbc:mysql://localhost/worlddb"
查看更多
登录 后发表回答