Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.sql.*;
- import java.util.Properties;
- public class MySQLSSLConnection {
- /**
- * MySQL SSLMode Type
- */
- enum SSLModeType {
- DISABLED, PREFERRED, REQUIRED, VERIFY_CA, VERIFY_IDENTITY;
- }
- private static final String DRIVER_CLASS_NAME = "com.mysql.cj.jdbc.Driver";
- private static final String MYSQL_JDBC_PREFIX = "jdbc:mysql://";
- // Database Connection Information
- private static final String host = "";
- private static final int port = 0;
- private static final String database = "";
- // Database User and Password
- private static final String USER = "";
- private static final String PASSWORD = "";
- private static Properties properties = new Properties();
- private static Connection connection;
- public static void main(String[] args) {
- try {
- onPrepare();
- onRun();
- onDestroy();
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- /**
- * Preparing for SSL connection setup
- */
- private static void onPrepare() throws ClassNotFoundException {
- Class.forName(DRIVER_CLASS_NAME);
- // SSL Mode
- properties.put("sslMode", SSLModeType.VERIFY_CA.name());
- properties.put("user", USER);
- properties.put("password", PASSWORD);
- }
- /**
- * Connecting MySQL database to SSL
- */
- private static void onRun() throws SQLException {
- String jdbcUrl = jdbcUrl(host, port, database);
- connection = DriverManager.getConnection(jdbcUrl, properties);
- String testQuery = "select version()";
- try (Statement statement = connection.createStatement();
- ResultSet resultSet = statement.executeQuery(testQuery)) {
- ResultSetMetaData resultSetMetaData = resultSet.getMetaData();
- int columnCount = resultSetMetaData.getColumnCount();
- while (resultSet.next()) {
- for (int i = 1; i <= columnCount; i++) {
- System.out.print(resultSet.getString(i) + "\t");
- }
- System.out.println();
- }
- } catch (SQLException e) {
- throw e;
- }
- }
- /**
- * Close Database Connection Resource
- */
- private static void onDestroy() throws SQLException {
- if (connection != null) {
- connection.close();
- }
- }
- /**
- * Generate and Return a MySQL JDBC URL
- *
- * @param host hostname or ip
- * @param port port number
- * @param database database name
- * @return String
- */
- private static String jdbcUrl(String host, int port, String database) {
- return MYSQL_JDBC_PREFIX + host + ":" + port + "/" + database;
- }
- }
Add Comment
Please, Sign In to add comment