Mark Meyers
Mark Meyers

Reputation: 563

JDBC for MySQL connection: works with MySQL Workbench, not with JDBC

I have a database server running on a bluehost machine, and I am giving myself remote IP access (via my IP address).

On my client machine, I have MySQL Workbench, and I have some Java code. MySQL workbench is getting the connection, using the database that I would like it to. With the driver manager connection, I cannot specify my database, such as with a forward slash after the port # in the URL, or it will give a connect error.

I can get the connection with the same userid and password using Workbench or the driver manager, but with JDBC it doesn't want to give me access to the same database.

When I try to execute this (JDBC): "use database", I get:

Access denied for user 'userid'@'184.11.22.%' to database 'database'

The URL I am using is

jdbc:mysql://(server-ip):(port)

If I try to append a '/(database)' on to the URL it gives the access violation. MySQL Workbench isn't getting any other special information, but appears to connect with the specified default schema. Same client machine; same user id and password. What is going wrong with the JDBC connection?

Java code added:

    db = DriverManager.getConnection(
        "jdbc:mysql://74.220.192.113/advanfc7_atm?" + 
        "user=(myuserid&password=(mypwd)");
    System.out.println("Connected.");
  statement = db.createStatement();
  statement.execute("use advanfc7_atm");
} catch (Exception e) {
  System.out.println("InitDB() "+e.getMessage());

}

I've also done it with 3 parameters to getConnection(), separating userid and password to the 2nd and 3rd params.

Upvotes: 0

Views: 2352

Answers (1)

Andy Guibert
Andy Guibert

Reputation: 42926

There is a small syntax error in your getConnection code:

db = DriverManager.getConnection(
        "jdbc:mysql://74.220.192.113/advanfc7_atm?" + 
        "user=(myuserid&password=(mypwd)");

Note that the closing parenthesis on user=(myuserid is missing. It should be user=(myuserid).

Instead:
Since each driver has different url syntax, it's generally safer to use the DriverManager.getConnection(String url, String user, String password) method instead.

Example usage:

db = DriverManager.getConnection(
        "jdbc:mysql://74.220.192.113/advanfc7_atm", 
        "myuserid",
        "mypwd");

Upvotes: 1

Related Questions