[筆記]Dotnet Core C# Insert資料到BigQuery

  • 175
  • 0

使用 C# Insert資料到BigQuery 實作範例

前置作業

參考 : https://www.dotblogs.com.tw/noncoder/2020/12/16/bigquery

新增資料表
圖解名詞
命名空間
using Google.Apis.Auth.OAuth2;
using Google.Apis.Bigquery.v2;
using Google.Apis.Bigquery.v2.Data;
using Google.Apis.Services;
using System.Security.Cryptography.X509Certificates;
主要程式
string serviceAccountEmail = "xxxxxx@xxxxxx-xxxxx.iam.gserviceaccount.com";
string rootPath = System.IO.Directory.GetCurrentDirectory();
string fileName = Path.Combine(rootPath, "xxxxxx-xxxxx-xxxxxxxxxxxx.p12");
var certificate = new X509Certificate2(fileName, "xxxxxxxxxx", X509KeyStorageFlags.MachineKeySet);

ServiceAccountCredential credential = new ServiceAccountCredential(
   new ServiceAccountCredential.Initializer(serviceAccountEmail)
   {
       Scopes = new[] { BigqueryService.Scope.DevstorageReadOnly, BigqueryService.Scope.Bigquery }
   }.FromCertificate(certificate));

var service = new BigqueryService(new BaseClientService.Initializer()
{
    HttpClientInitializer = credential,
    ApplicationName = "BigQuery API Test",
});



TableDataInsertAllRequest tbReq = new TableDataInsertAllRequest();
List<TableDataInsertAllRequest.RowsData> tabrows = new List<TableDataInsertAllRequest.RowsData>();
TableDataInsertAllRequest.RowsData rowData = new TableDataInsertAllRequest.RowsData();
IDictionary<string, object> row = new Dictionary<string, object>();
row.Add("TitleName", "SayHello");
row.Add("Code", "abcabc");
row.Add("TimesCount", "999");
rowData.Json = row;
tabrows.Add(rowData);
tbReq.Rows = tabrows;
tbReq.Kind = "bigquery#tableDataInsertAllRequest";
var insertTask = service.Tabledata.InsertAll(tbReq, "資源ID", "資料集ID", "資料表ID");

TableDataInsertAllResponse response = insertTask.Execute();