我正在尝试将连接字符串写入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;
<connectionStrings> <add name="Dbconnection" connectionString="Server=localhost; Database=OnlineShopping ; Integrated Security=True" ; providerName="System.Data.sqlClient" /> </connectionStrings>