简体   繁体   中英

How to get a manual connection to mysql using jdbc code?

I've seen this question a lot on the forum but all of the issues were slightly different so as not to apply so I'm going to ask it again. I've created a java web application that uses mysql as a backend. The mysql database is installed on a separate server from the web server. In mysql, I've created a user for my web application, defining the user's password, granted the user permissions and also define which IP Address the user may connect from. I've placed the database user info into the jdbc.properties file of the web application. The web application utilizes the Spring framework and when running on the web server it is able to connect to the database fine when Spring is managing the connection. However, I have one piece of code that requires me to manually connect to the database using jdbc code and when this piece of code runs, using the exact same database connection info as the spring-managed connection, I get the error:

<b>java.sql.SQLException: Access denied for user 'someuser'@'127.101.5.73' (

using password: YES)

I was pretty sure everything was correct since it works like a charm in my dev setup but it's not working in the test environment so something has got to be wrong. The code below is the code that I use to try to connect to the database. The propertiesMap variable holds the database info that was read from the jdbc.properties file:

private static void getResultSet(Map<String, String> propertiesMap, String sql) throws Exception {
try {
  // load the MySQL driver
  Class.forName("com.mysql.jdbc.Driver");

  // get the connection
  connect = DriverManager.getConnection(propertiesMap.get("jdbc.prod.url") + "?user=" 
          + propertiesMap.get("jdbc.prod.username") + "&password=" + propertiesMap.get("jdbc.prod.password"));

  // create the statement
  statement = connect.createStatement();

  // execute sql statement
  resultSet = statement.executeQuery(sql);

} catch (Exception e) {
  throw e;
}

}

The connection url in the above code resolves to:

jdbc:mysql://192.168.1.55:3306/somedatabase?user=someuser&password=somepassword

I'd appreciate any help anyone can offer.

From the exception you can tell that the code is behaving correctly. Try to grant the user access to the database:

GRANT ALL ON somedatabase.* TO 'username'@'127.101.5.73';

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