user1366330
user1366330

Reputation: 71

how to run sql statement sequentially one by one by just one call

HI i am trying to use this code -

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

for creating connection string from the connection string name from the webconfig file.

i m getting this error - Object reference not set to an instance of an object.

Please tell me how can i create one sql connection only by using the name of the connection string in the webconfig file.

Upvotes: 2

Views: 144

Answers (1)

Mike Perrenoud
Mike Perrenoud

Reputation: 67898

You don't want to build just one SqlConnection. You should never share connections. There are resource issues involved with that. When you want a connection, build it, open it, use it, and dispose it.

Further, when using the object you need to leverage the using statement:

var cString = ConfigurationManager
    .ConnectionStrings["train_debConnectionString"]
    .ConnectionString;
using (SqlConnection c = new SqlConnection(cString))
{
    using (SqlCommand cmd = new SqlCommand(sqlCmd, c))
    {

    }
}

UPDATE: if the issue is about getting to the connection string in a more concise manner, you can build a settings class on your own like this:

public static class AppSettings
{
    public static string ConnString
    {
        get
        {
            return ConfigurationManager
                .ConnectionStrings["train_debConnectionString"]
                .ConnectionString
        }
    }
}

and then do this:

using (SqlConnection c = new SqlConnection(AppSettings.ConnString))
{
    using (SqlCommand cmd = new SqlCommand(sqlCmd, c))
    {

    }
}

Upvotes: 4

Related Questions