2

我在 Visual Studio 2010 中的按钮后面有以下代码

private void button1_Click(object sender, EventArgs e)
{
    SqlCeConnection Con = new SqlCeConnection();

    Con.ConnectionString = "Data Source = 'DB.sdf';" + "Password='my Password';";

    SqlCeCommand Query = new SqlCeCommand("SELECT Password FROM Admin");

    try        
    {
       Con.Open();
    }
    catch(Exception ex)
    {
       MessageBox.Show(ex.Message);
    }

    SqlCeDataReader Reader=Query.ExecuteReader();
    MessageBox.Show(Reader["Password"].ToString());
}

它工作正常,执行和连接没有异常但是当我按下按钮时它会引发一个异常说

错误:执行阅读器连接属性尚未初始化

4

3 回答 3

2

我不会尝试在 UI 事件处理程序中评论数据库访问代码,它会过多地偏离答案。我要说的是,尽量不要这样做。

您没有命令构造函数或相关Connection属性中将连接与命令相关联。


我会将整个方法重写为以下内容,以消除危险的 try-catch(捕获所有内容,非常糟糕的做法)并利用事实using陈述也为您处理对象处理:

string password = null;

using (var conn = new SqlCeConnection("Data Source = 'AlviMBRental.sdf'; Password='my Password';"))
using (var comm = new SqlCeCommand("SELECT Password FROM Admin", conn))
{
    conn.Open();

    using (var reader = comm.ExecuteReader())
    {
        password = (string)reader["Password"];

    } // Dispose reader

    // Alternatively, if the resultset is single column and single row, you can do:
    var passwordScalar = (string)comm.ExecuteScalar();

} // Dispose command, close / dispose connection.

MessageBox.Show(password ?? "No password found.");
于 2012-06-12T14:01:03.617 回答
1

您没有将您的命令与您的连接相关联 - 试试这个:

SqlCeConnection Con = new SqlCeConnection("Data Source = 'AlviMBRental.sdf';Password='my Password';";

SqlCeCommand Query = new SqlCeCommand("SELECT Password FROM Admin", Con);  //   <== specify "Con" here!

否则,您SqlCeCommand将无法与之合作......

于 2012-06-12T14:01:29.467 回答
0

试试这样:

private void button1_Click(object sender, EventArgs e)
{
    var connectionString = "Data Source='AlviMBRental.sdf';Password='my Password';";
    using (var con = new SqlCeConnection(connectionString))
    using (var cmd = con.CreateCommand())
    {
        con.Open();
        cmd.CommandText = "SELECT Password FROM Admin";
        using (var reader = cmd.ExecuteReader())        
        {
            if (reader.Read())
            {
                MessageBox.Show(reader["Password"].ToString())
            }
        }
    }
}

确保您已将连接与命令对象相关联。还要确保您已将 IDisposable 对象包装using在我的示例中所示的语句中。

于 2012-06-12T14:03:08.997 回答