2016-10-05 39 views
0

我正在嘗試使用Java Rest WebService連接到JDBC使用SSL授權證書的Java MySQL連接

首先,我使用MySQL Workbench成功連接了用戶名和密碼以及一個額外的細節,我需要添加一個「SSL證書授權文件的路徑」並工作,我能夠連接和使用。使用數據庫遠程。

現在我試圖使用Java進行連接,這就是我想要的方式:我研究關於放入useSSL =在URL真正

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

,但沒有工作或本system.getproperties,我也p .pem文件在項目包和我的類包(因爲我不知道什麼地方我需要把文件)。

我該怎麼做才能連接?如果沒有這個SSL,數據庫拒絕我的連接,我試圖在另一類這種方式連接:

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

誰能幫助我?

回答

0

我的情況類似,但不相同。我可以從工作臺連接到MySQL,但不能從我的代碼連接到MySQL。在工作臺中選擇的唯一選項是useSSL(如果可用)。 下面的代碼在這種情況下適用於我。

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