ConfigurationManager.ConnectionStrings 屬性
定義
重要
部分資訊涉及發行前產品,在發行之前可能會有大幅修改。 Microsoft 對此處提供的資訊,不做任何明確或隱含的瑕疵擔保。
取得目前應用程式預設組態的 ConnectionStringsSection 資料。
public:
static property System::Configuration::ConnectionStringSettingsCollection ^ ConnectionStrings { System::Configuration::ConnectionStringSettingsCollection ^ get(); };
public static System.Configuration.ConnectionStringSettingsCollection ConnectionStrings { get; }
static member ConnectionStrings : System.Configuration.ConnectionStringSettingsCollection
Public Shared ReadOnly Property ConnectionStrings As ConnectionStringSettingsCollection
屬性值
目前應用程式預設組態的物件內容 ConnectionStringsSection 。
例外狀況
範例
下列範例示範如何使用 連接字串 從資料庫讀取數據。
using System;
using System.Configuration;
using System.Data.SqlClient;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
ReadProducts();
}
static void ReadProducts()
{
var connectionString = ConfigurationManager.ConnectionStrings["WingtipToys"].ConnectionString;
string queryString = "SELECT Id, ProductName FROM dbo.Products;";
using (var connection = new SqlConnection(connectionString))
{
var command = new SqlCommand(queryString, connection);
connection.Open();
using (var reader = command.ExecuteReader())
{
while (reader.Read())
{
Console.WriteLine(String.Format("{0}, {1}", reader[0], reader[1]));
}
}
}
}
}
}
Imports System.Configuration
Imports System.Data.SqlClient
Module Module1
Sub Main()
ReadProducts()
End Sub
Sub ReadProducts()
Dim connectionString = ConfigurationManager.ConnectionStrings("WingtipToys").ConnectionString
Dim queryString = "SELECT Id, ProductName FROM dbo.Products;"
Using connection As New SqlConnection(connectionString)
Dim command = New SqlCommand(queryString, connection)
connection.Open()
Using reader As SqlDataReader = command.ExecuteReader()
While reader.Read()
Console.WriteLine(String.Format("{0}, {1}", reader(0), reader(1)))
End While
End Using
End Using
End Sub
End Module
上述範例假設您的專案具有 App.config,如下所示。
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
<connectionStrings>
<add name="WingtipToys" connectionString="Data Source=(LocalDB)\v11.0;Initial Catalog=WingtipToys;Integrated Security=True;Pooling=False" />
</connectionStrings>
</configuration>
備註
ConnectionStringsSection物件包含組態檔區connectionStrings
段的內容。