系统.InvalidOperationException: 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();

}

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

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();

您需要提供连接字符串。

此外,您希望使用参数化查询来避免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();
        }
    }
}

相关内容

  • 没有找到相关文章

最新更新