简体   繁体   中英

Java MySQL Connection with SSL Authority Certificate

I am trying to connect using Java Rest WebService to a JDBC .

First I connected successfully using MySQL Workbench with username and password and one extra detail, I needed to add a "Path to Certificate Authority file for SSL" and worked, I was able to connect and use.I have the certificate to use the database remote.

Now I am trying to connect using Java and that is the way I am trying:

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");                                  
    }
}

I research about put useSSL=true in the URL but didn't work or this system.getproperties , I also p the .pem file in the project package and inside my class package (because I don't know what is the place I need to put the file).

What should I do to connect? Without this SSL, the database refuse my connection, and I am trying to connect in another class this way:

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

Can anyone help me?

My case was similar, but not same. I could connect to MySQL from workbench but not from my code. The only option selected in workbench was useSSL if Available. The code below worked for me in that case.

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();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM