0

我在尝试连接到本地数据库时遇到问题。我已经尝试了该网站上其他帖子的一些建议,但无济于事。任何帮助将不胜感激。以下是我到目前为止所拥有的。

private void button1_MouseClick(object sender, MouseEventArgs e)
{
    try
    {
        sConnection = "Server=(localdb)\Database1;Integrated Security=true;";

        dbConn = new SqlConnection(sConnection);
        dbConn.Open();

        sql = "SELECT * FROM Table2 ORDER" +
            "BY Customer name ASC;";
        dbCmd = new SqlCommand();
        dbCmd.CommandText = sql;
        dbCmd.Connection = dbConn;

        dbReader = dbCmd.ExecuteReader();

        while (dbReader.Read())
        {
            aMember = new member(dbReader["Name2"].ToString());
            this.listBox1.Items.Add(aMember);


        }

        dbReader.Close();
        dbConn.Close();
    }
    catch (System.Exception exc)
    {
        MessageBox.Show(exc.Message);
    }
}
4

3 回答 3

1

这里有几个我能想到的问题。我会讲两个。

1.连接字符串

您希望作为数据库而不是实例连接到“Database1”。首先尝试更改您的连接字符串。
将 sConnection 更改为:
string sConnection = "Server=(localdb);Initial Catalog=Database1;Integrated Security=true;";

2.使用语句(它的好处......


        var sConnection = "Server=(localdb);Initial Catalog=Database1;Integrated Security=true;";
        using (var sqlConn = new SqlConnection(sConnection))
        {
            sqlConn.Open();
            using (var cmd = sqlConn.CreateCommand())
            {
                cmd.CommandText = "SELECT * FROM Table2 ORDER BY [Customer Name]";

                using (var reader = cmd.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        aMember = new member(reader["Name2"].ToString());
                        this.listBox1.Items.Add(aMember); 
                    }
                }
            }
        }
于 2013-08-07T19:04:15.990 回答
0

正如 marc_s 所述:正确的连接字符串是“Server=(localdb)\v11.0;database=Database1;Integrated Security=true;”

于 2013-08-07T18:48:54.457 回答
0

我认为这就是问题所在。

sConnection = "Server=(localdb)\Database1;Integrated Security=true;";

检查这个

sConnection = "Server=(localdb)\\Database1;Integrated Security=true;";

从 .NET Framework 4.5 开始,您还可以连接到 LocalDB 数据库,如下所示:

server=(localdb)\\myInstance

检查此文档

于 2013-08-07T18:28:09.350 回答