我正在努力让我的数据库与我的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?");
    }
}

当前回答

当我在my.ini和php.ini文件中将mysql端口从3306更改为3307时,就发生了这种情况,但在更改端口(3307->3306)后,它又可以正常工作了。

其他回答

用于远程调用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'

在我的例子中,当我试图从同一个主机连接到运行在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中的绑定地址行。在这件事上他们都没帮上忙。

也许你没有启动你的Mysql和Apache服务器。我从XAMPP控制面板启动Apache服务器和Mysql后,连接成功建立。

好运!

示例jdbc连接类文件。当你想要获得一个连接时,简单地调用getConnection方法。包含相关的mysql-connector.jar

import java.sql.Connection;
import java.sql.DriverManager;


public class DBConnection {

    public Connection getConnection() {
        Connection con = null;

        String dbhost;
        String user;
        String password;
// get properties
dbhost="jdbc:mysql://localhost:3306/cardmaildb";
user="root";
password="123";

 System.out.println("S=======db Connecting======");

        try {
            Class.forName("com.mysql.jdbc.Driver");

            con = DriverManager.getConnection(dbhost, user, password);
            //if you are facing with SSl issue please try this 
            //con = DriverManager.getConnection("jdbc:mysql://192.168.23.100:3306/cardmaildb?useUnicode=yes&characterEncoding=UTF-8&useSSL=false",user, password);

        } catch (Exception e) {
            System.err.println("error in connection");
            e.printStackTrace();
        }
        System.out.println("E=======db Connecting======");
        return con;
    }

    public static void main(String[] args) {
        new DBConnection().getConnection();
    }
}

如果Java试图通过SSL连接MySQL,但出现了错误,也可能发生此错误。(在我的例子中,我将Payara Server 5.193.1连接池配置为MySQL。)

有人建议设置useSSL=false。但是,由于Connector/J版本8.0.13,该设置已弃用。下面是MySQL连接器/J 8.0配置属性的摘录:

sslMode By default, network connections are SSL encrypted; this property permits secure connections to be turned off, or a different levels of security to be chosen. The following values are allowed: DISABLED - Establish unencrypted connections; PREFERRED - (default) Establish encrypted connections if the server enabled them, otherwise fall back to unencrypted connections; REQUIRED - Establish secure connections if the server enabled them, fail otherwise; VERIFY_CA - Like REQUIRED but additionally verify the server TLS certificate against the configured Certificate Authority (CA) certificates; VERIFY_IDENTITY - Like VERIFY_CA, but additionally verify that the server certificate matches the host to which the connection is attempted. This property replaced the deprecated legacy properties useSSL, requireSSL, and verifyServerCertificate, which are still accepted but translated into a value for sslMode if sslMode is not explicitly set: useSSL=false is translated to sslMode=DISABLED; {"useSSL=true", "requireSSL=false", "verifyServerCertificate=false"} is translated to sslMode=PREFERRED; {"useSSL=true", "requireSSL=true", "verifyServerCertificate=false"} is translated to sslMode=REQUIRED; {"useSSL=true" AND "verifyServerCertificate=true"} is translated to sslMode=VERIFY_CA. There is no equivalent legacy settings for sslMode=VERIFY_IDENTITY. Note that, for ALL server versions, the default setting of sslMode is PREFERRED, and it is equivalent to the legacy settings of useSSL=true, requireSSL=false, and verifyServerCertificate=false, which are different from their default settings for Connector/J 8.0.12 and earlier in some situations. Applications that continue to use the legacy properties and rely on their old default settings should be reviewed. The legacy properties are ignored if sslMode is set explicitly. If none of sslMode or useSSL is set explicitly, the default setting of sslMode=PREFERRED applies. Default: PREFERRED Since version: 8.0.13

因此,在我的例子中,设置sslMode=DISABLED就是解决这个问题所需要的全部内容。 这是在一台测试机器上。但是对于生产环境,安全解决方案应该正确配置Java客户机和MySQL服务器以使用SSL。


注意,通过禁用SSL,您可能还必须设置allowPublicKeyRetrieval=true。(同样,从安全角度来看,这不是一个明智的决定)。进一步的信息提供在MySQL ConnectionString选项:

AllowPublicKeyRetrieval If the user account uses sha256_password authentication, the password must be protected during transmission; TLS is the preferred mechanism for this, but if it is not available then RSA public key encryption will be used. To specify the server’s RSA public key, use the ServerRSAPublicKeyFile connection string setting, or set AllowPublicKeyRetrieval=True to allow the client to automatically request the public key from the server. Note that AllowPublicKeyRetrieval=True could allow a malicious proxy to perform a MITM attack to get the plaintext password, so it is False by default and must be explicitly enabled.