LoginSignup
2
2

More than 5 years have passed since last update.

Windows 10 Pro x64 + VsCode で SQL Server 2016 Express にアクセスする .NET Core コンソールアプリを作成してみる

Posted at

目的

VsCode で SQL Server 2016 Express にアクセスするコンソールアプリを作成してみる
.NET Core で SQL CLR はと思ったけど Microsoft.SqlServer.Server が無いので無理?っぽい

初期設定

・VSCode を立ちあげて適当なフォルダを選択する
・ターミナルメニュー -> 新しいターミナルを選択
・ターミナルで dotnet new console [Enter]

launch.jsonの作成

デバックボタンの押下
 -> 'launch.json'の構成や修正の押下
  -> 環境の選択で -> NET Core と選択

launch.jsonの修正

修正前
"program": "${workspaceFolder}/bin/Debug/<insert-target-framework-here>/<insert-project-name-here>.dll",
修正後
"program": "${workspaceFolder}/bin/Debug/netcoreapp2.2/cmdexe.dll",

task.json の作成

デバッグメニュー
 -> デバック
  -> タスク'build'を見つけられませんでした
   -> タスクの構成ボタン押下
    -> テンプレートからタスクを生成 -> .Net Core .Net Core ビルドコマンドの実行

System.Data.SqlClientを追加する

表示メニュー
 -> コマンドパレット
  -> nuget
   -> Nuget package Manager:Add Pckage
    -> System.Data.SqlClient を入力後 enter
     -> System.Data.SqlClient を選択
      -> 4.6.0 を選択
cmdexe.csproj に以下が追加される

  <ItemGroup>
    <PackageReference Include="System.Data.SqlClient" Version="4.6.0"/>
  </ItemGroup>

サンプルコード


using System;
using System.Data.SqlClient;
namespace cmdexe
{
    class cmdexe
    {
        static void Main(string[] args)
        {
            SqlConnectionStringBuilder constr = new SqlConnectionStringBuilder();
            constr["Data Source"] = "xxx.xxx.xxx.xxx";
            constr["User ID"] = "demo";
            constr["Password"] = "demo";
            constr["Initial Catalog"] = "demo";
            constr["Trusted_Connection"] = true;

            SqlConnection con = new SqlConnection(constr.ConnectionString);
            con.Open();
            try {
                SqlCommand oc = new SqlCommand("select * from ZIPCODE WHERE seq = '00000001'",con);
                SqlDataReader odr = oc.ExecuteReader();
                while (odr.Read() == true) {
                    Console.WriteLine(odr["POSTAL"]);
                }
                odr.Close();
            }
            finally {
                con.Close();
            }
        }
    }
}

参考にしたのは以下のサイト

dotnet new

2
2
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
2