LoginSignup
2
1

C# で Azure Databricks に ODBC 接続する方法

Posted at

はじめに

Azure Databricks ではクラスターや SQL Warehouse に対して ODBC 接続が可能です。
今回は C# を使用してクラスターに ODBC 接続する方法を説明します。
環境は Windows 10 、VSCode 1.87.0 となります。

手順

1. VSCode Extention のインストール

VSCode にて C# Dev KitNuGet Package Manager をインストールします。

2. .NET SDK のインストール

以下のページにてダウンロードした .NET インストーラーを実行します。

3. ODBC Driver のインストール

以下のページにてダウンロードした ODBC Driver インストーラーを実行します。

4. ODBC パッケージのインストール

VSCode にて NuGet Package Manager を利用して System.Data.Odbc パッケージをインストールします。

5. テーブルの準備

Databricks ワークスペースにて、以下のコードをノートブックで実行してテーブルを作成します。

%sql
CREATE TABLE odbctest
(
    name string,
    age int,
    address string
)
%sql
insert into odbctest  values('hoge',50,'tokyo');
insert into odbctest  values('fuga',51,'osaka');

6. コード編集

以下のコマンドを実行して、新規プロジェクトを作成します。

$ dotnet new console -o "SampleConsole"

自動作成された Program.cs を以下のように編集します。
変数 tablehosthttppathpwd の値は自分の環境に合わせて変更しましょう。

using System;
using System.Data;
using System.Data.Odbc;

string table = "hive_metastore.default.odbctest";
string selectSQL = $"select * from {table}";

string driver = "{Simba Spark ODBC Driver}";
string host = "adb-1234567890123456.78.azuredatabricks.net";
string httppath = "sql/protocolv1/o/1234567890123456/1234-567890-mi123456";
string pwd = "dapi12345678901234567890";
string connectionString = $"Driver={driver};Host={host};Port=443;HTTPPath={httppath};UID=token;PWD={pwd};SSL=1;ThriftTransport=2;transportMode=http;AuthMech=3;";

using (OdbcConnection conn = new OdbcConnection(connectionString))
{
    try
    {
        conn.Open();
        using (OdbcCommand command = conn.CreateCommand())
        {
            command.CommandText = selectSQL;
            using (OdbcDataReader reader = command.ExecuteReader())
            {
                while (reader.Read())
                {
                    Console.WriteLine("{0}", reader.GetFieldType(0));
                    Console.WriteLine("{0}", reader.GetValue(0));
                }
            }
        }
    }
    catch (OdbcException ex)
    {
        Console.WriteLine(ex.Message);
    }
}

なお、プロキシを経由する場合は接続文字列が以下のようになります。

string connectionString = $"Driver={driver};Host={host};Port=443;HTTPPath={httppath};UID=token;PWD={pwd};SSL=1;ThriftTransport=2;transportMode=http;AuthMech=3;ProxyHost=10.0.0.5;ProxyPort=3128;UseProxy=1;";

認証方式は Databricks トークンを利用しています。これは Databricks ワークスペースにて取得できます。

image.png

ODBC 接続文字列は Databricks ワークスペースのクラスター画面で確認できます。

image.png

7. コード実行

以下のコマンドでコードを実行します。テーブルの値が取得できることを確認します。

$ dotnet run
System.String
hoge
System.String
fuga

おわりに

C# で Azure Databricks に ODBC 接続する方法を説明しました。
今回はコード内に認証情報を記載していますが、ODBC データ ソース アドミニストレーターを起動して DSN 設定を行うことでも認証は可能です。

参考

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1