简体   繁体   中英

How do I avoid an 'unknown database' error when using a custom database directory?

I'm working on a project and I have put my database folder in project folder. How can I make a database connection to any directory rather than just default MySQL dir in Java?

String MySQLURL = "jdbc:mysql://localhost:3306/C:\\Program Files\\SnakeGame";

String UserName = "root";
String Password = "admin";
Connection con = null;
try {
    con = DriverManager.getConnection(MySQLURL,UserName,Password);
    if (con != null) {
        System.out.println("Database connection is successful !!!!");
    }
} catch (Exception e) {
    e.printStackTrace();
}

When doing this, I get this error:

java.sql.SQLSyntaxErrorException: Unknown database 'c:\program files\snakegame'

Your connection URL is wrong

String MySQLURL = "jdbc:mysql://localhost:3306/C:\\Program Files\\SnakeGame";

I am not sure why your MySQLURL contains C:\Program Files\SnakeGame

The connection URL for the mysql database is jdbc:mysql://localhost:3306/[DatabaseName]

Where jdbc is the API, mysql is the database, localhost is the server name on which mysql is running (we may also use the server's IP address here), 3306 is the port number, and [DatabaseName] is the name of the database created on the MySQL server.

Replace the [DatabaseName] name accordingly after creating the database in MySQL server

Combining localhost:3306/ with C:\\Program Files\\SnakeGame makes little sense for any database - either you're trying to connect to a file-based database (in which case the localhost... part makes no sense) or you're working with a server-based one (in which case the C:\... part makes no sense.

Also, this connection string would make little sense for a file-based database either because you didn't specify a specific file, just a path.

Incidentally, MySQL is server-based, not file-based. It's expecting a database name after the localhost:3306/ part, not a path (hence the error). The physical location of the actual database program is an installation/configuration issue - it has nothing to do with how you actually connect to the database server once it's already running.

Think about it this way: when you call an external database, web service, or web site, do you need to know which physical folder it's deployed to? Obviously not. The physical folders involved are completely irrelevant when calling MySQL or another database like this.

One of the comments pointed this out, but did you intend to use SQlite or some other file-based database here instead?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM