Question

SqlConnection con = new SqlConnection(@"Data Source=(LocalDB)\v11.0;Integrated Security=True;AttachDbFilename=c:\users\name\documents\visual studio 2013\Projects\DBSample\DBSample\Database1.mdf");
SqlCommand cmd = new SqlCommand("Select * From Account", con);
SqlDataReader rd= cmd.ExecuteReader(); ;

This is my code for connecting to database1.mdf but it is not working.

I saw other post that this should already work

Was it helpful?

Solution

You are not opening the connection,you need to open connection with databases before executing query.

do like this:

SqlConnection con = new SqlConnection(@"Data Source=(LocalDB)\v11.0;Integrated Security=True;AttachDbFilename=c:\users\name\documents\visual studio 2013\Projects\DBSample\DBSample\Database1.mdf");
SqlCommand cmd = new SqlCommand("Select * From Account", con);
con.Open();
SqlDataReader rd= cmd.ExecuteReader();

Explanation:

Other examples you read probably use an SqlDataAdapter which opens the connection for you. If you use an SqlCommand directly, however, you need to open the connection yourself.

OTHER TIPS

Since you're not providing any details on what exact Exception you are having, I'll go with the obvious: your connection has not been opened by the time you attempt to execute your SQL query. Not only that but your objects never gets disposed of either.

A better implementation would be this:

using (SqlConnection con = new SqlConnection(@"Data Source=(LocalDB)\v11.0;Integrated Security=True;AttachDbFilename=c:\users\name\documents\visual studio 2013\Projects\DBSample\DBSample\Database1.mdf"))
{
    using (SqlCommand cmd = new SqlCommand("Select * From Account", con))
    {
        // here the connection opens
        con.Open();

        using (SqlDataReader rd = cmd.ExecuteReader())
        {
            // do your data reading here
        }
    }
}

The using statement will make sure your con, cmd and rd objects gets disposed of properly.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top