System.InvalidOperationException:ExecuteReader:尚未初始化Connection属性

时间:2014-07-23 17:15:21

标签: c# asp.net .net executereader

protected void Button3_Click(object sender, EventArgs e)
{
 cn.Open();

 SqlCommand cmd = new SqlCommand("select top '"+Label4.Text+"' * from qb_vb where marks=1");

 SqlDataReader dr1 = cmd.ExecuteReader();

if (dr1.Read())
 {
  Label8.Text = dr1["quest"].ToString();
  Label9.Text = dr1["ans1"].ToString();
 }
cn.Close();

}

2 个答案:

答案 0 :(得分:5)

您需要将命令与您打开的连接相关联:

cn.Open();
SqlCommand cmd = new SqlCommand("select top '"+Label4.Text+"' * from qb_vb where marks=1");
cmd.Connection = cn; // <------ THIS MUST BE ADDED
SqlDataReader dr1 = cmd.ExecuteReader();
if (dr1.Read())
{
    Label8.Text = dr1["quest"].ToString();
    Label9.Text = dr1["ans1"].ToString();
}
cn.Close();

答案 1 :(得分:1)

您需要提供Connection String

此外,您希望使用参数化查询来避免SQL注入。

protected void Button3_Click(object sender, EventArgs e)
{
    string connectionString = "Data Source=(local);" +
                              "Initial Catalog=DATABASE_NAME;" +
                              "Persist Security Info=True;" +
                              "User ID=USER_ID;" +
                              "Password=PASSWORD";

    string cmdText = "SELECT TOP (@Count) * FROM qb_vb WHERE marks=1";

    using (var cnn = new SqlConnection(connectionString ))
    {
        var cmd = new SqlCommand(cmdText, cnn);
        cmd.CommandType = CommandType.Text;
        cmd.Parameters.AddWithValue("@Count", Label4.Text);

        cnn.Open();

        SqlDataReader dr1 = cmd.ExecuteReader();

        if (dr1.Read())
        {
            Label8.Text = dr1["quest"].ToString();
            Label9.Text = dr1["ans1"].ToString();
        }
    }
}