LocalDB(.mdf)的连接字符串无法在WPF上运行

时间:2014-04-09 13:24:17

标签: c# .net ado.net data-access

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(); ;

这是我连接database1.mdf的代码,但它不起作用。

我看到其他帖子说这应该已经有效了

2 个答案:

答案 0 :(得分:5)

您没有打开连接,需要在执行查询之前打开与数据库的连接。

这样做:

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();

<强>解释

您阅读的其他示例可能使用 SqlDataAdapter ,它会为您打开连接。但是,如果直接使用 SqlCommand ,则需要自己打开连接。

答案 1 :(得分:1)

由于您没有提供有关您所拥有的Exception的具体内容的任何详细信息,因此我将明确指出:当您尝试执行SQL查询时,您的连接尚未打开。不仅如此,你的对象也永远不会被处置掉。

更好的实施方式是:

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
        }
    }
}

using语句将确保您的concmdrd个对象得到妥善处理。

相关问题