C# · 12月 29, 2021

c# – 如何在web.config文件中编写连接字符串并从中读取?

我正在尝试将连接字符串写入Web.config,如下所示: <connectionStrings> <add name=”Dbconnection” connectionString=”Server=localhost; Database=OnlineShopping ; Integrated Security=True”/></connectionStrings >

并从中读取:

string strcon = ConfigurationManager.ConnectionStrings[“Dbconnection”].ConnectionString;sqlConnection DbConnection = new sqlConnection(strcon);

当运行程序时,我得到一个错误,因为null引用.但是当我使用这个代码:

sqlConnection DbConnection = new sqlConnection();DbConnection.ConnectionString = “Server=localhost; Database=OnlineShopping ; Integrated Security=True”;

我没有得到任何错误,程序正常工作!
问题是什么?

解决方法 添加引用添加System.Configuration: – System.Configuration.ConfigurationManager. ConnectionStrings[“connectionStringName”].ConnectionString;

您也可以更改WebConfig文件以包含提供程序名称:

<connectionStrings> <add name=”Dbconnection” connectionString=”Server=localhost; Database=OnlineShopping ; Integrated Security=True” ; providerName=”System.Data.sqlClient” /></connectionStrings>