gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 01:46:43 29 4
gpt4 key购买 nike

我通过 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/T-s- 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

最佳答案

做这个 similar question on ServerFault 的任何答案帮助?

1) Verify the address mysql is bound to, it's probably 127.0.0.1 (only) which I believe is the default (at least on standard Ubuntu server). You'll have to comment out the bind-address parameter in my.cnf to bind to all available addresses (you can't choose multiple, it's one or all).

2) If it is bound to 127.0.0.1 and you can't connect using "localhost", make sure it's not resolving to the IPv6 localhost address instead of IPv4. (or just use the IP address)

3) Double and triple-check the port that mysql is listening on.

4) Make sure you're using the right JDBC connector for your JDK.

5) Make sure you're not doing something really silly like starting mysql with --skip-networking.

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

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

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com