ConfigurationManager.ConnectionStrings 属性
public static ConnectionStringSettingsCollection ConnectionStrings { get; }
App.config
1 <?xml version="1.0" encoding="utf-8" ?> 2 <configuration> 3 <startup> 4 <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" /> 5 </startup> 6 <connectionStrings> 7 <add name="WingtipToys" connectionString="Data Source=(LocalDB)\v11.0;Initial Catalog=WingtipToys;Integrated Security=True;
Pooling=False" /> 8 </connectionStrings> 9 </configuration>
如何使用连接字符串从数据库读取数据。
1 using System; 2 using System.Configuration; 3 using System.Data.SqlClient; 4 5 namespace ConsoleApplication1 6 { 7 class Program 8 { 9 static void Main(string[] args) 10 { 11 ReadProducts(); 12 } 13 14 static void ReadProducts() 15 { 16 var connectionString = ConfigurationManager.ConnectionStrings["WingtipToys"].ConnectionString; 17 string queryString = "SELECT Id, ProductName FROM dbo.Products;"; 18 using (var connection = new SqlConnection(connectionString)) 19 { 20 var command = new SqlCommand(queryString, connection); 21 connection.Open(); 22 using (var reader = command.ExecuteReader()) 23 { 24 while (reader.Read()) 25 { 26 Console.WriteLine(String.Format("{0}, {1}", reader[0], reader[1])); 27 } 28 } 29 } 30 } 31 } 32 }