C# 无法从SQL Server Compact获取输出

C# 无法从SQL Server Compact获取输出,c#,sql-server-ce,C#,Sql Server Ce,我在VisualStudio2010中的按钮后面有以下代码 private void button1_Click(object sender, EventArgs e) { SqlCeConnection Con = new SqlCeConnection(); Con.ConnectionString = "Data Source = 'DB.sdf';" + "Password='my Password';"; SqlCeCommand Query = new S

我在VisualStudio2010中的按钮后面有以下代码

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());
}
它运行良好,执行连接时没有异常,但当我按下按钮时,它会引发异常

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

我不会试图在UI事件处理程序中对数据库访问代码进行注释,这会使答案偏离太多。我要说的是,尽量不要这样做

您尚未将连接与命令相关联,无论是在中还是相关的中。 我会将整个方法重新编写为以下内容,以避免危险的尝试-抓住一切,非常糟糕的做法,并利用事实-使用语句也为您处理对象处理:

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.");

您没有将命令与连接关联-请尝试以下操作:

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

SqlCeCommand Query = new SqlCeCommand("SELECT Password FROM Admin", Con);  //   <== specify "Con" here!
否则,您的SqlCeCommand没有连接,无法使用……

请尝试以下操作:

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对象,如我的示例所示