无法从SQL Server Compact获取输出

时间:2012-06-12 13:57:47

标签: c# sql-server-ce

我在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());
}

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

  

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

3 个答案:

答案 0 :(得分:2)

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

您尚未在command constructor或相关Connection property中将连接与命令相关联。

<小时/> 我会将整个方法重写为以下内容以删除危险的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.");

答案 1 :(得分: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无法使用....

答案 2 :(得分: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())
            }
        }
    }
}

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