【问题标题】:Java MySQL Connection with SSL Authority Certificate带有 SSL 授权证书的 Java MySQL 连接
【发布时间】:2016-10-05 02:06:19
【问题描述】:

我正在尝试使用 Java Rest WebService 连接到 JDBC

首先,我使用 MySQL Workbench 成功连接了用户名和密码以及一个额外的细节,我需要添加一个“SSL 证书颁发机构文件的路径”并且工作,我能够连接和使用。我有证书可以使用数据库远程。

现在我正在尝试使用 Java 进行连接,这就是我正在尝试的方式:

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

public class ConexaoBD {
    // Define o Metodo de Conexao quando a classe � chamada
    static {
        try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
    }

    public Connection obtemConexao() throws SQLException {
        System.getProperties().setProperty("javax.net.ssl.trustStore","/mysqlcertificate.pem");
        return DriverManager.getConnection("jdbc:mysql://myHost", "myUsername", "myPassword");                                  
    }
}

我研究了在 URL 中放置 useSSL=true 但没有用或者这个system.getproperties,我还在项目包和我的类包中添加了.pem 文件(因为我不知道什么是我需要放置文件的地方)。

我应该怎么做才能连接?如果没有这个 SSL,数据库会拒绝我的连接,我正在尝试以这种方式连接另一个类:

Connection conn = null;
Statement stm = null;
try {
    ConexaoBD bd = new ConexaoBD();
    conn = bd.obtemConexao();

谁能帮帮我?

【问题讨论】:

    标签: java mysql ssl jdbc


    【解决方案1】:

    我的情况类似,但不一样。我可以从工作台连接到 MySQL,但不能从我的代码连接到 MySQL。在工作台中选择的唯一选项是 useSSL if Available。 在这种情况下,下面的代码对我有用。

    private String db_server = BaseMethods.getSystemData("db_server");
    private String db_user = BaseMethods.getSystemData("db_user");
    private String db_password = BaseMethods.getSystemData("db_password");
    
    private void connectToDb() throws Exception {
        String jdbcDriver = "com.mysql.jdbc.Driver";
        String dbUrl = "jdbc:mysql://" + db_server +
            "?verifyServerCertificate=false" +
            "&useSSL=true" +
            "&requireSSL=true";
        System.setProperty(jdbcDriver, "");
        Class.forName(jdbcDriver).newInstance();
    
        Connection conn = DriverManager.getConnection(dbUrl, db_user, db_password);
        Statement statement = conn.createStatement();
    }
    

    【讨论】:

      猜你喜欢
      • 2019-02-14
      • 2017-03-28
      • 2012-01-14
      • 1970-01-01
      • 2019-04-26
      • 2019-12-11
      • 1970-01-01
      • 2018-04-04
      • 2015-07-04
      相关资源
      最近更新 更多