如何在web.config文件中编写连接字符串并从中读取 [英] how to write connection string in web.config file and read from it
本文介绍了如何在web.config文件中编写连接字符串并从中读取的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试将Connectionstring写入Web.config,如下所示:
i'm trying to write Connectionstring to Web.config like this:
<connectionStrings>
<add name="Dbconnection" connectionString="Server=localhost; Database=OnlineShopping ; Integrated Security=True"/>
</connectionStrings >
并阅读就像这样:
and read from it like this:
string strcon = ConfigurationManager.ConnectionStrings["Dbconnection"].ConnectionString;
SqlConnection DbConnection = new SqlConnection(strcon);
运行progrom时
我收到错误因为空引用。
但是当我使用这段代码时:
when run the progrom 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";
我没有收到任何错误,程序工作正常!
有什么问题?
Tanx!
I don't get any error and the program work correctly!
What is the problem?
Tanx!
推荐答案
<connectionstrings>
<add name="Your Connection string name" connectionstring="data source=server name;Database=database name;uid=Database Username;pwd=password;multipleactiveresultsets=true;" providername="System.Data.SqlClient" />
</connectionstrings>
For Call Connection string write the below code
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["Connection string name"].ConnectionString.ToString());
Connection string name means "Your Connection string name"
检查您的Web.config连接字符串。
Check your Web.config Connection string.
<connectionStrings>
<add name="Dbconnection" connectionString="Data Source=localhost;Initial Catalog=OnlineShopping;Integrated Security=true" providerName="System.Data.SqlClient" />
没有'除了缺少初始目录之外,您的连接字符串似乎有任何问题。您已将其指定为数据库,但在连接字符串中,我们将其指定为初始目录。所以,重新编写你的连接字符串,然后再试一次:
There doesn't seem anything wrong with your connection string other than the 'Initial Catalog' missing from it. You have specified it as Database, but in a connection string, we specify it as Initial Catalog. So, re-write your connection string as below and try again:
<connectionStrings>
<add name="Dbconnection" connectionString="Server=localhost;Initial Catalog=OnlineShopping;Integrated Security=True"/>
</connectionStrings >
佛详细信息,您可以访问 http://msdn.microsoft.com/en-us/library/ms178411 .aspx [ ^ ]同样。
这篇关于如何在web.config文件中编写连接字符串并从中读取的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文