在C#中配置和使用ConnectionStrings,可以通過在應(yīng)用程序的配置文件(App.config或Web.config)中進(jìn)行配置。以下是一個示例:
<configuration>
<connectionStrings>
<add name="MyConnectionString" connectionString="Data Source=server;Initial Catalog=database;User Id=username;Password=password;" providerName="System.Data.SqlClient" />
</connectionStrings>
</configuration>
using System;
using System.Configuration;
using System.Data.SqlClient;
class Program
{
static void Main()
{
string connectionString = ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
// 執(zhí)行查詢等操作
}
}
}
在代碼中通過ConfigurationManager類的ConnectionStrings屬性可以獲取配置文件中的ConnectionStrings,并使用SqlConnection類來創(chuàng)建數(shù)據(jù)庫連接。