我正在努力让我的数据库与我的Java程序对话。

有人能给我一个使用JDBC的快速而简单的示例程序吗?

我得到了一个相当大的错误

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. The driver has not received any packets from the server.
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:513)
    at com.mysql.jdbc.Util.handleNewInstance(Util.java:409)
    at com.mysql.jdbc.SQLError.createCommunicationsException(SQLError.java:1122)
    at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2260)
    at com.mysql.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:787)
    at com.mysql.jdbc.JDBC4Connection.<init>(JDBC4Connection.java:49)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:513)
    at com.mysql.jdbc.Util.handleNewInstance(Util.java:409)
    at com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:357)
    at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:285)
    at java.sql.DriverManager.getConnection(DriverManager.java:582)
    at java.sql.DriverManager.getConnection(DriverManager.java:207)
    at SqlTest.main(SqlTest.java:22)
Caused by: com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure
    The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:513)
    at com.mysql.jdbc.Util.handleNewInstance(Util.java:409)
    at com.mysql.jdbc.SQLError.createCommunicationsException(SQLError.java:1122)
    at com.mysql.jdbc.MysqlIO.<init>(MysqlIO.java:344)
    at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2181)
    ... 12 more
Caused by: java.net.ConnectException: Connection refused
    at java.net.PlainSocketImpl.socketConnect(Native Method)
    at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:333)
    at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:195)
    at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:182)
    at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:432)
    at java.net.Socket.connect(Socket.java:529)
    at java.net.Socket.connect(Socket.java:478)
    at java.net.Socket.<init>(Socket.java:375)
    at java.net.Socket.<init>(Socket.java:218)
    at com.mysql.jdbc.StandardSocketFactory.connect(StandardSocketFactory.java:256)
    at com.mysql.jdbc.MysqlIO.<init>(MysqlIO.java:293)
    ... 13 more

测试文件内容:

import com.mysql.jdbc.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class SqlTest {

    public static void main(String [] args) throws Exception {
        // Class.forName( "com.mysql.jdbc.Driver" ); // do this in init
        // // edit the jdbc url 
        Connection conn = DriverManager.getConnection( 
            "jdbc:mysql://localhost:3306/projects?user=user1&password=123");
        // Statement st = conn.createStatement();
        // ResultSet rs = st.executeQuery( "select * from table" );

        System.out.println("Connected?");
    }
}

当前回答

这个问题有很多答案,我认为我的答案更适合另一个问题,但那个问题的答案是锁定的。它指向这个线程。

解决这个问题的方法是在application.properties中将&createDatabaseIfNotExist=true附加到spring.datasource.url字符串中。

这是非常棘手的,因为它表现为几个不同的、奇怪的、看似不相关的错误,当我试图修复它所抱怨的东西时,它只是弹出另一个错误,或者错误是不可能修复的。它抱怨无法加载JDBC,说它不在类路径中,但我以大约30种不同的方式将它添加到类路径中,并且已经是facedesking了。

其他回答

用于远程调用Mysql

Add remote user to Mysql from for exemple IP=remoteIP : mysql -u xxxx -p //local coonection to mysql mysql> GRANT ALL PRIVILEGES ON *.* TO 'theNewUser'@'remoteIP' IDENTIFIED BY 'passWord'; //Query OK, 0 rows affected (xx sec) mysql> FLUSH PRIVILEGES; //Query OK, 0 rows affected Allow remote access to Mysql (by default all externall call is not allowed): Edit /etc/mysql/mysql.conf.d/mysqld.cnf or /etc/mysql/my.cnf Change line: bind-address = 127.0.0.1 to bind-address = 0.0.0.0 Restart Mysql: /etc/init.d/mysql restart For The latest version of JDBC Driver, the JDBC : jdbc.url='jdbc:mysql://remoteIP:3306/yourDbInstance?autoReconnect=true&amp;useUnicode=true&amp;useJDBCCompliantTimezoneShift=true&amp;useLegacyDatetimeCode=false&amp;serverTimezone=UTC' jdbc.user='theNewUser'

我有同样的连接错误: 我的问题是我使用MySQL 8.0.15,但Java连接器是5.x.x。

下面是我如何修复它。 1. 下载8.0.15。从Maven存储库: https://search.maven.org/search?q=g:mysql%20AND%20a:mysql-connector-java

在Eclipse IDE中,在资源管理器中选择“引用库” 鼠标右键>生成路径>配置生成路径 A.删除“mysql-connector-5.x.jar” b.单击“Add External JARs…”,选择“mysql-connector-java-8.0.15.jar”。

重新运行,问题就解决了。

刚刚经历过。

必须做到: (这可以放在静态块初始化器中)

static{ // would have to be surrounded by try catch
    Class.forName("com.mysql.jdbc.Driver");   // this will load the class Driver
}

也可以通过以下方式获得连接:

conn = DriverManager.getConnection(DBURL,<username>,<password>);

而不是指定登录参数

  Connection conn = DriverManager.getConnection( "jdbc:mysql://localhost:3306/projects?user=user1&password=123");

的问候。

在我的例子中,当我试图从同一个主机连接到运行在Ubuntu主机虚拟机容器中的mysql-server时,我遇到了这个错误。

例子: 如果我的虚拟机名称是abc.company.com,下面的jdbc URL将不起作用:

jdbc: mysql: / / abc.company.com: 3306 / dbname

上面的jdbc url可以在其他机器上正常工作,如xyz.company.com,但不是abc.company.com。

下面的jdbc URL可以在abc.company.com的机器上正常工作:

jdbc: mysql: / / localhost: 3306 / dbname

这让我检查了/etc/hosts文件。

添加以下行到/etc/hosts可以修复此问题:

127.0.1.1 ABC

这似乎是一个操作系统错误,需要我们在一些Ubuntu版本上添加这些。 参考:https://www.debian.org/doc/manuals/debian-reference/ch05.en.html # _the_hostname_resolution

在尝试这个之前,我已经尝试了所有其他的解决方案,如GRANT all ..,修改mysql.cnf中的绑定地址行。在这件事上他们都没帮上忙。

我解决了两件事: 1. 使用以下connads创建非root的新用户:

CREATE USER 'newuser'@'localhost' IDENTIFIED BY 'password';
GRANT ALL PRIVILEGES ON *.* TO 'newuser'@'localhost';
FLUSH PRIVILEGES;

2. 注释mysqld.conf中的IP地址行

然后用新的用户名和密码连接。它应该会起作用。