LoginSignup
5
4

More than 1 year has passed since last update.

DBの接続情報をApp.configで指定する

Last updated at Posted at 2023-01-10

DBの接続情報をハードコードしていたため、App.configで指定する方法に変更した。

使用ツール:
SQLServer

指定方法

ソリューションエクスプローラーからApp.configファイルを開く。

<configuration></configuration>
の中に、以下の設定を記述していく。

App.config
<connectionStrings>
    <add name="sqlsvrconnect"
    connectionString="Data Source=Db12345;User Id=hoge;Password=pass;Initial Catalog=DBNAME"
    providerName="System.Data.SqlClient"/>
</connectionStrings>

<記述情報に関する説明> SQLServer接続時に入力する情報をそのまま記述する
Data Source = サーバ名(S)
User Id = ログイン(L)
Password = パスワード(P)
Initial Catalog = 使用したいデータベース名

指定した設定の取得方法

必要なusing記述

using System.Configuration;

※using System.Configurationの記述だけでうまくいかない場合、ソリューションエクスプローラーにある参照を右クリックして、参照の追加を選択。
System.Configurationを検索して、チェックボックスにチェックを入れると使用できるようになる。

App.configで指定した接続文字列を取得する

[]の中にはadd nameで指定した名前を入れる。

string connStr = ConfigrationManager.ConnectionStrings["sqlsvrconnect"].ConnectionString;

おまけ

ハードコードで接続文字列を書く場合

string connStr = @"Data Source=Db12345;User Id=hoge;Password=pass;Initial Catalog=DBNAME";

5
4
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
5
4