简体   繁体   中英

Unable to connect to mysql jdbc database

I am frustrated seeing this error and not knowing the solution. I am trying to connect to a mysql db with a server url but it is giving my mysqlException(stacktrace below). The code works fine till here:

String dbUrl = "jdbc:mysql://server_url/db_name";
String driver = "com.mysql.jdbc.Driver";
Class.forName(driver).newInstance();
String user = "user";
String password = "password";
conn = DriverManager.getConnection(dbUrl,user,password);

This is the error I'm getting

java.sql.SQLException: null,  message from server: "Host '172.23.251.154' is not allowed to connect to this MySQL server"
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:946)
    at com.mysql.jdbc.MysqlIO.doHandshake(MysqlIO.java:1070)
    at com.mysql.jdbc.Connection.createNewIO(Connection.java:2775)
    at com.mysql.jdbc.Connection.<init>(Connection.java:1555)
    at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:285)
    at java.sql.DriverManager.getConnection(DriverManager.java:582)
    at java.sql.DriverManager.getConnection(DriverManager.java:185)

Is this because I'm using a different version of mysql-connector jar? Please help me.

From Chapter 6. SQL Questions: How Do I Enable TCP Connections to MySQL? ,

By default, MySQL won't allow ANY users access to any of the databases if they connect over a TCP connection. In order to permit the connection, you must create a entry in the user table of the mysql database (make sure you select the PASSWORD function to encrypt your password). In particular, the Host field needs to indicate which host(s) are permitted to connect. If you specify % (which I would not recommend), then a user would be able to connect from any host.

那么3306端口上的防火墙呢?

May be the user you are trying to access doesn't have enough privileges to access the database from the given server.

So try providing GRANTS to the user.

GRANT ALL PRIVILEGES ON database_name TO 'user'@'hostname' IDENTIFIED BY PASSWORD <password>;
FLUSH PRIVILEGES;

here hostname can be your host address "172.23.251.154". Dont forget to flush privileges and then try connecting the server.

如果您的MySql服务器位于主机提供程序上,则控制面板中会提供一个选项,您可以在其中设置ip地址,在这种情况下,您可以从该IP地址连接到mysql服务器172.23.251.154(如果这是您的IP地址)

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