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

前端之家收集整理的这篇文章主要介绍了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>
原文链接:https://www.f2er.com/csharp/94069.html

猜你在找的C#相关文章