MySQL配置SSL之后的JAVA连接MySQL的代码

MySQL配置SSL之后的JAVA连接MySQL的代码

代码之前的工作:
1、mysql已经正确配置好ssl(openssl证书)
2、授权用户只可以用ssl方式连接(这里例子是用户:admin、密码:admin)

以下是java代码的实现(用mysql驱动的MysqlDataSource实现  开始用的mysql-connector-java-5.0.4-bin.jar 不支持
换了5.1.30 可行)

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;


public class DBUtil {
private static String USERNAME = "admin";
private static String PASSWORD= "admin";
private static String HOST = "localhost";
private static int PORT = 3306;
private static String DATABASE = "compass";
//keystore路径    参数字符串必须是  file:/ XXXXX类型
private static String KEYSTORE_PATH = "file:/D:/myssl/keystore";
//密码
private static String  KEYSTORE_PASSWORD = "123456";
private static String TRUSTORE_PATH = "file:/D:/myssl/truststore";
private static String  TRUSTORE_PASSWORD = "123456";
/**
*

Description:


* @param args
* @return void
* @author LinwangFan
* @time 2014-11-21 上午10:29:00
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Statement stm = null;
ResultSet res = null;
Connection conn = null;
MysqlDataSource mysqlDS=null;
try{
mysqlDS = new MysqlDataSource();
mysqlDS.setUseSSL(true);
mysqlDS.setRequireSSL(true);
mysqlDS.setVerifyServerCertificate(true);
mysqlDS.setLogger("com.mysql.jdbc.log.StandardLogger");


mysqlDS.setClientCertificateKeyStoreType("JKS");
mysqlDS.setClientCertificateKeyStoreUrl(KEYSTORE_PATH);
mysqlDS.setClientCertificateKeyStorePassword(KEYSTORE_PASSWORD);


mysqlDS.setTrustCertificateKeyStoreType("JKS");
mysqlDS.setTrustCertificateKeyStoreUrl(TRUSTORE_PATH);
mysqlDS.setTrustCertificateKeyStorePassword(TRUSTORE_PASSWORD);

mysqlDS.setServerName(HOST);
mysqlDS.setPort(PORT);
mysqlDS.setUser(USERNAME);
mysqlDS.setPassword(PASSWORD);
mysqlDS.setDatabaseName(DATABASE);
conn = mysqlDS.getConnection();
stm = conn.createStatement();
res = stm.executeQuery("SELECT * FROM system_parameter");
while(res.next()){
System.out.println(res.getString(1));
}
}catch(Exception e){
e.printStackTrace();
} finally {
try {
if (res != null)
res.close();
if (stm != null)
stm.close();
if (conn != null)
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}


}


你可能感兴趣的:(MySQL)