通过Java连接到MySQL时出现异常。我下载了MySQL Java连接器并将其添加到classpath中。我试图连接到MySQL表,但没有成功。
我也尝试过telnet localhost 3306,但得到了以下错误:“nodename或servname提供,或不知道”
代码如下:

//import java.sql.Connection;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

public class ConnectToDatabase {

    public static void main(String[] args) throws Exception{
        //Accessing driver from the JAR file
        Class.forName ("com.mysql.jdbc.Driver").newInstance ();

        Connection con = DriverManager.getConnection(
            "jdbc:mysql://localhost:3306/cldatabase", "root", "root");

        //Here we create our query
        PreparedStatement statement = con.prepareStatement(
            "SELECT * FROM profiles");

        ResultSet result = statement.executeQuery();
        while(result.next()){
        System.out.println(result.getString("firstName") + " " +
            result.getString("lastName"));
    }
}

引发了此异常:
Exception in thread "main" com.mysql.jdbc.exceptions.jdbc4.
    CommunicationsException: Communications link failure

The last packet sent successfully to the server was 0 milliseconds ago.

我的mac上安装了xampp。
这就是我运行“ps-ef | grep mysql”时出现的情况
0 1694 1 0:00.02??0:00.03/bin/sh/Applications/XAMPP/XAMPP file s/bin/mysqld_safe--datadir=/Applications/XAMPP/xamppfiles/var/mysql--pid file=/Applications/XAMPP/xamppfiles/var/mysql/T-s-smackook-Air.local.pid
-2 1792 1694 0:00.07??0:00.28/Applications/XAMPP/xamppfiles/sbin/mysqld--basedir=/Applications/XAMPP/xamppfiles--datadir=/Applications/XAMPP/xamppfiles/var/mysql--user=nobody--log error=/Applications/XAMPP/xamppfiles/var/mysql/k-Air.local.err--pid file=/Applications/XAMPP/xamppfiles/var/mysql/-MacBook-Air.local.pid--socket=/Applications/XAMPP/xamppfiles/var/mysql/mysql.sock--port=3306
501 1814 1484 0:00.00 ttys000 0:00.00 grep mysql

最佳答案

这个similar question on ServerFault的答案有帮助吗?
1)验证mysql地址是否绑定
可能是127.0.0.1(仅限)
我认为是违约
至少在标准的Ubuntu服务器上)。
你得评论一下
将my.cnf中的地址参数绑定到
绑定到所有可用地址(您
不能选择多个,一个或
全部)。
2)如果绑定到127.0.0.1,则
无法使用“localhost”连接,使
确定它没有解析到IPv6
本地主机地址而不是IPv4。(或
只需使用IP地址)
3)双重和三重检查端口
mysql正在监听的。
4)确保使用正确的
JDK的JDBC连接器。
5)确保你没有
一些很愚蠢的事情比如
带有--跳过网络的mysql。
当你运行“lsof -i :3306”时会得到什么?

关于java - 无法使用Java连接到mysql数据库,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/5105172/

10-11 04:12
查看更多