3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

ConnectionString の作成・パースに ConnectionStringBuilder を使う

Posted at

ADO.NET でデータベースに接続するとき、接続文字列 (ConnectionString) を指定しますが、接続文字列の作成・パースを簡単にするためのクラスが提供されています。

System.Data.Common 名前空間に DbConnectionStringBuilder という基底クラスがあり、各データベース向けにこれを継承したクラスがあります。

SQL Server の場合は SqlConnectionStringBuilder です。

接続文字列の作成

// using System.Data.SqlClient;

var builder = new SqlConnectionStringBuilder();
builder.DataSource = "ServerName";
builder.InitialCatalog = "AdventureWorks";
builder.IntegratedSecurity = true;

var connectionString = builder.ConnectionString;
Console.WriteLine(connectionString);
// => "Data Source=ServerName;Initial Catalog=AdventureWorks;Integrated Security=True"

接続文字列のパース

// using System.Data.SqlClient;

var connectionString = "Network Address=(local);Integrated Security=SSPI;Initial Catalog=AdventureWorks";
var builder = new SqlConnectionStringBuilder(connectionString);

Console.WriteLine("DataSource: " + builder.DataSource);
// => "DataSource: (local)"
Console.WriteLine("IntegratedSecurity: " + builder.IntegratedSecurity);
// => "IntegratedSecurity: True"
Console.WriteLine("InitialCatalog: " + builder.InitialCatalog);
// => "InitialCatalog: AdventureWorks"
3
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
3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?