Oracle JDBC

This post is how to connect to oracle from JDBC.

There are four main connection examples:

TCP to Single Host
  1. jdbc:oracle:thin:@(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=<HOST>)(PORT=<PORT>))(CONNECT_DATA=(SERVICE_NAME=<SERVICE_NAME>)))
TCP to Multiple Hosts
  1. jdbc:oracle:thin:@(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=<HOST1>)(PORT=<PORT1>))(ADDRESS=(PROTOCOL=TCP)(HOST=<HOST2>)(PORT=<PORT2>))(CONNECT_DATA=(SERVICE_NAME=<SERVICE_NAME>)))
SSL to Single Host
  1. jdbc:oracle:thin:@(DESCRIPTION=(ADDRESS=(PROTOCOL=TCPS)(HOST=<HOST>)(PORT=<PORT>))(CONNECT_DATA=(SERVICE_NAME=<SERVICE_NAME>)))
SSL to Multiple Hosts
  1. jdbc:oracle:thin:@(DESCRIPTION=(ADDRESS=(PROTOCOL=TCPS)(HOST=<HOST1>)(PORT=<PORT1>))(ADDRESS=(PROTOCOL=TCPS)(HOST=<HOST2>)(PORT=<PORT2>))(CONNECT_DATA=(SERVICE_NAME=<SERVICE_NAME>)))
Connect Using PySpark With Databricks

You will need to get the secret from a keyvault. Refer to Databricks: Get Secret

  1. secret = <Get_Secret>
  2.  
  3. df = spark.read \
  4. .format("jdbc") \
  5. .option("url", "<URL>") \
  6. .option("dbtable", "<SCHEMA>.<TABLE>") \
  7. .option("user", "<ACCOUNT>") \
  8. .option("password", secret) \
  9. .option("driver", "oracle.jdbc.driver.OracleDriver") \
  10. .laod()
Connect Using SQL With Databricks

It should be noted that this isn’t a really good way and I don’t believe is completely secure.

Add cluster configuration

  1. spark.databricks.secureVariableSubstitute.enabled false
  2. spark.<SOME_VARIABLE_NAME> {{secrets/<SCOPE>/<SECRET>}}

Code

  1. %sql
  2.  
  3. CREATE SCHEMA IF NOT EXISTS <SCHEMA_NAME>;
  4.  
  5. DROP VIEW IF EXISTS <VIEW_NAME>;
  6.  
  7. CREATE TEMPORARY VIEW <SCHEMA_NAME>.<VIEW_NAME>
  8. USING org.apache.spark.sql.jdbc
  9. OPTIONS (
  10. url "<URL>",
  11. dbtable "<SCHEMA_NAME>.<TABLE_NAME>",
  12. user "<ACCOUNT>",
  13. password "${spark.<SOME_VARIABLE_NAME>}",
  14. driver "oracle.jdbc.driver.OracleDriver"
  15. )

 

Spark Connector Connect to SQL Server

This post is how to use the Spark Connector to Connect to SQL Server.

Install Spark Connector

  1. spark-mssql-connector_2.12-1.2.0.jar

Install msal

  1. pip install msal

Connect using Azure SPN

  1. import msal
  2. global_token_cache = msal.TokenCache()
  3.  
  4. secret = "<GET SECRET SECURELY>"
  5.  
  6. global_spn_app = msal.ConfidentialClientApplication(
  7. <CLIENT_ID>, Authority='https://login.microsoftonline.com/<TENANT_ID>',
  8. client_credential=secret,
  9. token_cache=global_token_cache,
  10. )
  11.  
  12. result = global_spn_app.acquire_token_for_client(scopes=['https://database.windows.net//.default'])
  13.  
  14. jdbc_df = spark.read \
  15. .format("com.microsoft.sqlserver.jdbc.spark") \
  16. .option("url", 'jdbc:sqlserver://<SERVER_NAME>:<PORT>;database=<DATABASE>;') \
  17. .option("query", "SELECT * FROM SOMETHING") \
  18. .option("accessToken", result['access_token']) \
  19. .option("encrypt", "true") \
  20. .option("hostNameInCertificate", "*.database.windows.net") \
  21. .load()

Connect using Domain Auth

  1. secret = "<GET SECRET SECURELY>"
  2.  
  3. jdbc_df = spark.read \
  4. .format("com.microsoft.sqlserver.jdbc.spark") \
  5. .option("url", 'jdbc:sqlserver://<SERVER_NAME>:<PORT>;database=<DATABASE>;') \
  6. .option("query", "SELECT * FROM SOMETHING") \
  7. .option("authentication", "ActiveDirectoryPassword") \
  8. .option("user", "<USER>@<DOMAIN>") \
  9. .option("password", "<SECRET>") \
  10. .load()

Connect using SQL Auth

I do not recommend SQL Auth

  1. secret = "<GET SECRET SECURELY>"
  2.  
  3. jdbc_df = spark.read \
  4. .format("com.microsoft.sqlserver.jdbc.spark") \
  5. .option("url", 'jdbc:sqlserver://<SERVER_NAME>:<PORT>;database=<DATABASE>;') \
  6. .option("query", "SELECT * FROM SOMETHING") \
  7. .option("user", "<USER>") \
  8. .option("password", "<SECRET>") \
  9. .load()

 

 

 

Phoenix & Java: Connecting Secure

In this tutorial I will show you how to connect to an Secure Phoenix using Java. It’s rather straight forward.

POM.xml

  1. <dependency>
  2. <groupId>org.apache.phoenix</groupId>
  3. <artifactId>phoenix-queryserver</artifactId>
  4. <version>5.0.0-HBase-2.0</version>
  5. </dependency>

Imports:

  1. import java.io.IOException;
  2. import java.sql.Connection;
  3. import java.sql.DriverManager;
  4. import java.sql.SQLException;
  5. import java.sql.ResultSet;
  6. import java.sql.Statement;

Initiate Kerberos Authentication

  1. System.setProperty("java.security.krb5.conf", "C:\\Program Files\\Java\\jdk1.8.0_171\\jre\\lib\\security\\krb5.conf");
  2. System.setProperty("java.security.krb5.realm", "REALM.CA");
  3. System.setProperty("java.security.krb5.kdc", "REALM.CA");
  4. System.setProperty("sun.security.krb5.debug", "true");
  5. System.setProperty("javax.net.debug", "all");

Connect:

Now we create the connection.

  1. Class.forName("org.apache.phoenix.jdbc.PhoenixDriver");
  2. String url = "jdbc:phoenix:hadoop:2181:/hbase-secure:hbase/hadoop@REALM.CA:\\data\\hbase.service.keytab";
  3. Connection connection = DriverManager.getConnection(url);
  4.  
  5. System.out.println("Connected");
  6.  
  7. Statement statement = connection.createStatement();
  8.  
  9. //Drop table
  10. String deleteTableSql = "DROP TABLE IF EXISTS employee";
  11. System.out.println("Deleting Table: " + deleteTableSql);
  12. statement.executeUpdate(deleteTableSql);
  13. System.out.println("Created Table");
  14. //Create a table
  15. String createTableSql = "CREATE TABLE employee ( eid bigint primary key, name varchar)";
  16. System.out.println("Creating Table: " + createTableSql);
  17. statement.executeUpdate(createTableSql);
  18. System.out.println("Created Table");
  19.  
  20. //Insert Data
  21. String insertTableSql = "UPSERT INTO employee VALUES(1, 'Oliver')";
  22. System.out.println("Inserting Data: " + insertTableSql);
  23. statement.executeUpdate(insertTableSql);
  24. System.out.println("Inserted Data");
  25.  
  26. connection.commit();
  27.  
  28. //Select Data
  29. String selectTablesSql = "select * from employee";
  30. System.out.println("Show records: " + selectTablesSql);
  31. ResultSet res = statement.executeQuery(selectTablesSql);
  32. while (res.next()) {
  33. System.out.println(String.format("id: %s name: %s", res.getInt("eid"), res.getString("name")));
  34. }

 

 

 

 

 

Hive & Java: Connect to Remote Kerberos Hive using KeyTab

In this tutorial I will show you how to connect to remote Kerberos Hive cluster using Java. If you haven’t install Hive yet follow the tutorial.

Import SSL Cert to Java:

Follow this tutorial to “Installing unlimited strength encryption Java libraries

If on Windows do the following

  1. #Import it
  2. "C:\Program Files\Java\jdk1.8.0_171\bin\keytool" -import -file hadoop.csr -keystore "C:\Program Files\Java\jdk1.8.0_171\jre\lib\security\cacerts" -alias "hadoop"
  3.  
  4. #Check it
  5. "C:\Program Files\Java\jdk1.8.0_171\bin\keytool" -list -v -keystore "C:\Program Files\Java\jdk1.8.0_171\jre\lib\security\cacerts"
  6.  
  7. #If you want to delete it
  8. "C:\Program Files\Java\jdk1.8.0_171\bin\keytool" -delete -alias hadoop -keystore "C:\Program Files\Java\jdk1.8.0_171\jre\lib\security\cacerts"

POM.xml:

  1. <dependency>
  2. <groupId>org.apache.hive</groupId>
  3. <artifactId>hive-jdbc</artifactId>
  4. <version>2.3.3</version>
  5. <exclusions>
  6. <exclusion>
  7. <groupId>jdk.tools</groupId>
  8. <artifactId>jdk.tools</artifactId>
  9. </exclusion>
  10. </exclusions>
  11. </dependency>

Imports:

  1. import org.apache.hadoop.conf.Configuration;
  2. import org.apache.hadoop.security.UserGroupInformation;
  3. import java.sql.SQLException;
  4. import java.sql.Connection;
  5. import java.sql.ResultSet;
  6. import java.sql.Statement;
  7. import java.sql.DriverManager;

Connect:

  1. // Setup the configuration object.
  2. final Configuration config = new Configuration();
  3.  
  4. config.set("fs.defaultFS", "swebhdfs://hadoop:50470");
  5. config.set("hadoop.security.authentication", "kerberos");
  6. config.set("hadoop.rpc.protection", "integrity");
  7.  
  8. System.setProperty("https.protocols", "TLSv1,TLSv1.1,TLSv1.2");
  9. System.setProperty("java.security.krb5.conf", "C:\\Program Files\\Java\\jdk1.8.0_171\\jre\\lib\\security\\krb5.conf");
  10. System.setProperty("java.security.krb5.realm", "REALM.CA");
  11. System.setProperty("java.security.krb5.kdc", "REALM.CA");
  12. System.setProperty("sun.security.krb5.debug", "true");
  13. System.setProperty("javax.net.debug", "all");
  14. System.setProperty("javax.net.ssl.keyStorePassword","changeit");
  15. System.setProperty("javax.net.ssl.keyStore","C:\\Program Files\\Java\\jdk1.8.0_171\\jre\\lib\\security\\cacerts");
  16. System.setProperty("javax.net.ssl.trustStore", "C:\\Program Files\\Java\\jdk1.8.0_171\\jre\\lib\\security\\cacerts");
  17. System.setProperty("javax.net.ssl.trustStorePassword","changeit");
  18. System.setProperty("javax.security.auth.useSubjectCredsOnly", "false");
  19.  
  20. UserGroupInformation.setConfiguration(config);
  21. UserGroupInformation.setLoginUser(UserGroupInformation.loginUserFromKeytabAndReturnUGI("hive/hadoop@REALM.CA", "c:\\data\\hive.service.keytab"));
  22.  
  23. System.out.println(UserGroupInformation.getLoginUser());
  24. System.out.println(UserGroupInformation.getCurrentUser());
  25.  
  26. //Add the hive driver
  27. Class.forName("org.apache.hive.jdbc.HiveDriver");
  28.  
  29. //Connect to hive jdbc
  30. Connection connection = DriverManager.getConnection("jdbc:hive2://hadoop:10000/default;principal=hive/hadoop@REALM.CA");
  31. Statement statement = connection.createStatement();
  32.  
  33. //Create a table
  34. String createTableSql = "CREATE TABLE IF NOT EXISTS "
  35. +" employee ( eid int, name String, "
  36. +" salary String, designation String)"
  37. +" COMMENT 'Employee details'"
  38. +" ROW FORMAT DELIMITED"
  39. +" FIELDS TERMINATED BY '\t'"
  40. +" LINES TERMINATED BY '\n'"
  41. +" STORED AS TEXTFILE";
  42.  
  43. System.out.println("Creating Table: " + createTableSql);
  44. statement.executeUpdate(createTableSql);
  45.  
  46. //Show all the tables to ensure we successfully added the table
  47. String showTablesSql = "show tables";
  48. System.out.println("Show All Tables: " + showTablesSql);
  49. ResultSet res = statement.executeQuery(showTablesSql);
  50.  
  51. while (res.next()) {
  52. System.out.println(res.getString(1));
  53. }
  54.  
  55. //Drop the table
  56. String dropTablesSql = "DROP TABLE IF EXISTS employee";
  57.  
  58. System.out.println("Dropping Table: " + dropTablesSql);
  59. statement.executeUpdate(dropTablesSql);
  60.  
  61. System.out.println("Finish!");