简体   繁体   English

可以使用Java而不是PHP连接到MySQL数据库吗?

[英]Can connect to MySQL db with java but not with PHP?

I have a java application, that can connect to an online MySQL database, like this: 我有一个Java应用程序,可以连接到在线MySQL数据库,如下所示:

private String hostName = "db4free.net:3306";
private String dbName = "mydbname";
private String username = "name";
private String password = "pw";
   try {
    Class.forName("com.mysql.jdbc.Driver");
    connection = DriverManager.getConnection("jdbc:mysql://" + hostName + "/" + dbName, username, password);
    System.out.println("Connection established!");
   } catch (Exception ex) {
        ex.printStackTrace();
   }

It works perfectly. 它运作完美。 However, I try the same with PHP (ignore hostname difference, this should be it): 但是,我尝试与PHP相同(忽略主机名的区别,应该是这样):

$host = "85.10.205.173"; 
$dbname = "dbname"; 
$username = "name"; 
$password = "pw"; 

$options = array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8'); 

try 
{ 
    // Open connection with db
    $db = new PDO("mysql:host={$host};dbname={$dbname};charset=utf8", $username, $password, $options); 
} 
catch(PDOException $ex) 
{ 
    // Just an error message, if connection fails
    die("Failed to connect to the database: " . $ex->getMessage()); 
}

And after a while, I get this: SQLSTATE[HY000] [2003] Can't connect to MySQL server on '85.10.205.173' (4) 过了一会儿,我得到了:SQLSTATE [HY000] [2003]无法连接到'85 .10.205.173'上的MySQL服务器(4)

So why do the two work differently? 那么,为什么两者的工作方式有所不同? I think that remote access is enabled (because I could connect with java). 我认为启用了远程访问(因为我可以使用Java连接)。

Disable the DNS hostname lookups in mysql mysql禁用DNS主机名查找

To disable DNS host name lookups, start the server with the --skip-name-resolve option. 要禁用DNS主机名查找,请使用--skip-name-resolve选项启动服务器。 In this case, the server uses only IP addresses and not host names to match connecting hosts to rows in the MySQL grant tables. 在这种情况下,服务器仅使用IP地址而不使用主机名来将连接的主机与MySQL授权表中的行进行匹配。 Only accounts specified in those tables using IP addresses can be used. 只能使用这些表中使用IP地址指定的帐户。

Don't forget to restart MySQL to take effect. 不要忘记重启MySQL才能生效。

Not sure this will solve your problem. 不确定这是否可以解决您的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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