문제

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

도움이 되었습니까?

해결책

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.

다른 팁

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top