如何写连接字符串中的web.config文件,并从中读取? [英] How to write connection string in web.config file and read from it?

查看:133
本文介绍了如何写连接字符串中的web.config文件,并从中读取?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想写的连接字符串到Web.config中是这样的:

I'm trying to write Connection string to Web.config like this:

<connectionStrings>
  <add name="Dbconnection" connectionString="Server=localhost; 
       Database=OnlineShopping ; Integrated Security=True"/>
</connectionStrings >

和来自像这样写着:

string strcon = 
    ConfigurationManager.ConnectionStrings["Dbconnection"].ConnectionString;
SqlConnection DbConnection = new SqlConnection(strcon);

在运行该程序,我得到因空引用错误。但是当我用这个code:

when run the program I get an error because of the null reference. but when I use this code:

SqlConnection DbConnection = new SqlConnection();
DbConnection.ConnectionString = 
    "Server=localhost; Database=OnlineShopping ; Integrated Security=True";

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

I don't get any error and the program works correctly! What is the problem?

推荐答案

添加引用添加 System.Configuration : -

Add reference to add System.Configuration:-

System.Configuration.ConfigurationManager.
    ConnectionStrings["connectionStringName"].ConnectionString;

你也可以改变WebConfig文件以包括供应商名称: -

Also you can change the WebConfig file to include the provider name:-

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

这篇关于如何写连接字符串中的web.config文件,并从中读取?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆