SqlConnection in C#

£可爱£侵袭症+ 提交于 2019-12-07 09:21:28

问题


In VB.NET I can use:

Protected Conn As New SqlConnection(ConfigurationManager.ConnectionStrings("Active").ConnectionString)

However, when I do the following in C#:

protected SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings("conn"));

I get the error:

The name 'ConfigurationManager' does not exist in the current context

Then if I change it to:

protected SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings("conn"));

I get the error:

Non-invocable member 'System.Configuration.ConfigurationManager.ConnectionStrings' cannot be used like a method.

Why is this and how can I connect to my SQL Server database using C#?


回答1:


Try like this:

protected SqlConnection conn = new SqlConnection(
    ConfigurationManager.ConnectionStrings["conn"].ConnectionString
);

Notice the [] instead of () which is what is used to access an element of an array in C#. Also notice the usage of the .ConnectionString property call as the SqlConnection constructor expects a string.




回答2:


Change the last pair of parentheses to square brackets. In C#, parentheses are used in method calls, whether square brackets are used to access members inside a collection (or so).

In addition, use the using clause to ensure that the connection is always closed and disposed when you go out of scope:

using (SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["conn"]))
{
...
}

Read about it here: http://msdn.microsoft.com/en-us/library/yh598w02(v=vs.80).aspx




回答3:


In C#, you read collections using square bracket syntax:

e.g.

string[] strings = new[] { "first", "second", "third" };

string secondString = strings[1];

So you access the Configuration collection like this:

ConfigurationManager.ConnectionStrings["conn"];


来源:https://stackoverflow.com/questions/7139440/sqlconnection-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!