首页 文章

无法使用Java连接到mysql数据库

提问于
浏览
2

我有一个通过Java连接到MySQL的异常 . 我下载了MySQL Java连接器并将其添加到 classpath . 我正在尝试连接到MySQL表但没有成功 .

我也试过 telnet localhost 3306 ,但得到以下错误: "nodename nor servname provided, or not known"

代码如下:

//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 0:00.02 ?? 0:00.03 / bin / sh / Applications / XAMPP / xamppfiles / bin / mysqld_safe --datadir = / Applications / XAMPP / xamppfiles / var / mysql --pid-file = / Applications / XAMPP / xamppfiles / var / mysql / Ts- sMacBook-Air.local.pid -2 1792 1694 0 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 0:00.00 ttys000 0:00.00 grep mysql

2 回答

  • 3

    对此similar question on ServerFault的任何答案有帮助吗?

    1)验证mysql绑定的地址,它可能是127.0.0.1(仅),我认为是默认的(至少在标准的Ubuntu服务器上) . 您必须将my.cnf中的bind-address参数注释掉以绑定到所有可用的地址(您不能选择多个,它是一个或全部) . 2)如果它绑定到127.0.0.1并且您无法使用“localhost”进行连接,请确保它不会解析为IPv6 localhost地址而不是IPv4 . (或者只使用IP地址)3)对mysql正在侦听的端口进行双重和三重检查 . 4)确保为JDK使用正确的JDBC连接器 . 5)确保你没有像使用--skip-networking启动mysql那样做一些非常愚蠢的事情 .

    当你运行“ lsof -i :3306 ”时你会得到什么?

  • 1

    如果您在Class.forName(“com.mysql.jdbc.Driver”)上遇到问题;然后在以下位置复制mysql连接器..确定它将工作..C:\ Program Files \ Apache Software Foundation \ Tomcat 7.0 \ webapps \ lib \ WEB-INF..note在webapps文件夹中没有名为lib的目录然后手动创建lib和WEB-INF目录并在其中粘贴mysql连接器 . 不需要任何类路径设置.....

    如果你仍然遇到问题然后发送你的查询......

相关问题