自己投資としてチャレンジしている内容を Blog で公開しています。
今回は C# で SQL Server に接続し Select 結果を Azure Blob Storage に保存する方法について紹介します。今流行りの ChatGPT (https://chat.openai.com/) 無料版 (2023/02 時点) を利用して C# のコードを教えてもらいながら実装しました。
▼1. SQL Server on Ubntu への接続および Select 結果を Azure Blob Storage に保存
以前 Java および Python により SQL Server の検索結果を Azure Blob Storage にファイルとして保存する方法について紹介していました。今回 C# を使て実装します。
Java – MySQL 検索結果を Azure Blob Storage に保存 No.86
Python -SQL Server on Ubuntu 検索結果をAzure Blob Storageに保存 No96
▼2. 事前準備
Ubuntu 20.4 で Visual Studio Code 開発環境にて C# を使い SQL Server へ接続する環境の構築方法は以下を参考にしてください。
C# SQL Server on Ubuntu20.04 に接続する方法 VS Code No.104
▼3. SQLClient で SQL Server に接続し Select 結果を CSVファイルとして Azure Blob Storage に出力する C# コード
3-1. アプリケーションの作成し、作成したディレクトリで VSCode を起動
$dotnet new console -o TestApp2302
$cd TestApp2302
$code .
$ls
obj Program.cs TestApp2302.csproj
3-2. TestApp2302.csproj に System.Data.SqlClient および Azure.Storage.Blobs を追加し保存 (Ctrl+ s)
SQL Server への接続に必要な .NET Data Provider for SQL Server の名前空間 System.Data.SqlClient を登録します。2022/12 の最新 Version 4.8.5 を指定しています。
また Azure Blob Storage の操作に必要な 名前空間 Azure.Storage.Blobs も併せて登録します。2022/12 の最新 12.14.1 を指定します。
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <TargetFramework>net6.0</TargetFramework> <ImplicitUsings>enable</ImplicitUsings> <Nullable>enable</Nullable> </PropertyGroup> <ItemGroup> <PackageReference Include="System.Data.SqlClient" Version="4.8.5"/> <PackageReference Include="Azure.Storage.Blobs" Version="12.14.1"/> </ItemGroup> </Project>
- C# Ubuntu (sqlchoice.azurewebsites.net)
- System.Data.SqlClient 名前空間 | Microsoft Learn
- BlobContainerClient Class (Azure.Storage.Blobs) – Azure for .NET Developers | Microsoft Learn
- NuGet Gallery | System.Data.SqlClient
- NuGet Gallery | Azure.Storage.Blobs 12.14.1
3-3. 追加した System.Data.SqlClient を Project に反映
dotnet restore
3-4. ChatGPT に Blob へのファイルアップロードのコードを教えてもらう
csv ファイルの blob Storage への upload 方法が分からないので、ChatGPT (https://chat.openai.com/) に聞く。ChatGPT の使い方は他の blog を参照ください。
3-5. C# のコード Program.cs 作成
コード内の Bold の部分の Blob や SQL Server に関するパラメータは環境に合わせて変更します。
using System.IO;
using System.Data.SqlClient;
using Azure.Storage.Blobs;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
// set path to local file etc
String localpath = @"/home/xxx/TestApp2302/data.csv";
String ConnectionString = "DefaultEndpointsProtocol=https;AccountName=xxxx;AccountKey=xxx;EndpointSuffix=core.windows.net";
String containerName = "file";
String blobName = "data.csv";
try
{
// Build connection string
SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder();
builder.DataSource = "localhost";
builder.UserID = "sa";
builder.Password = "password";
builder.InitialCatalog = "sampledb1";
// Connect to SQL
Console.Write("Connecting to SQL Server ... ");
using (SqlConnection connection = new SqlConnection(builder.ConnectionString))
{
connection.Open();
Console.WriteLine("Done.");
// execute select query
String sql = "SELECT id, cdatetime, note FROM sampletb";
using (SqlCommand command = new SqlCommand(sql, connection))
{
using (SqlDataReader reader = command.ExecuteReader())
{
// save data to csv file
using (System.IO.StreamWriter file = new System.IO.StreamWriter(localpath))
{
while (reader.Read())
{
file.WriteLine("{0},{1},{2}", reader.GetInt32(0), reader.GetDateTime(1), reader.GetString(2));
}
}
}
}
}
}
catch (SqlException e)
{
Console.WriteLine(e.ToString());
}
// Create a container and a blob client
BlobServiceClient blobServiceClient = new BlobServiceClient(ConnectionString);
BlobContainerClient container = blobServiceClient.GetBlobContainerClient(containerName);
BlobClient blob = container.GetBlobClient(blobName);
// Upload the file to the blob
using (FileStream uploadFileStream = File.OpenRead(localpath))
{
blob.Upload(uploadFileStream, true);
uploadFileStream.Close();
}
Console.WriteLine("\nUploaded to Blob storage as blob:\n\t {0}\n", blob.Uri);
Console.WriteLine("Blob uploaded");
}
}
}
3-6. 実行結果
エラーなく実行した結果が以下です。data.csv のファイルが作成され Azure Blob Storage に Upload されたことを確認します。
$ dotnet run
Connecting to SQL Server ... Done.
Uploaded to Blob storage as blob:
https://xxx.blob.core.windows.net/file/data.csv
Blob uploaded
出力された data.csv ファイルの中身を確認。
cat data.csv
3366109,12/9/2022 1:59:12 PM,int
3366109,12/9/2022 1:59:12 PM,mcranentiv
6732218,12/9/2022 1:59:12 PM,orlsojlvuu
10098327,12/9/2022 1:59:12 PM,uaclnlkehv
13464436,12/9/2022 1:59:12 PM,xngcehsmtc
16830545,12/9/2022 1:59:12 PM,llvzgooqaa
20196654,12/9/2022 1:59:12 PM,atmordnpfz
23562763,12/9/2022 1:59:12 PM,qpzlferdra
26928872,12/9/2022 1:59:12 PM,lnbjlmclxx
30294981,12/9/2022 1:59:12 PM,xfspqvetbf
0,12/9/2022 1:59:12 PM,Description
852,1/7/2023 4:07:53 PM,Description
▼4. 参考情報
- https://code.visualstudio.com/docs/setup/linux
- C# SQL Server on Ubuntu20.04 に接続する方法 VS Code No.104
- System.Data.SqlClient 名前空間 | Microsoft Learn
- BlobContainerClient Class (Azure.Storage.Blobs) – Azure for .NET Developers | Microsoft Learn
- ChatGPT (https://chat.openai.com/) 無料版 (2023/02 時点)
以上です。参考になりましたら幸いです。