日期:2014-05-17  浏览次数:20432 次

coun(*)返回值问题?
C# code
private void _btn()
    {
        string sql = "select count(*) from [dhk_qiankuan] where user_name='" + ddl_name.SelectedItem.Text + "'";
        SqlConnection con = new SqlConnection(conString);
        con.Open();
        SqlCommand cmd = new SqlCommand(sql, con);
        int sum = (int)cmd.ExecuteNonQuery();
        if (sum == 0)
        {
            btn_submit.Visible = false;
        }
        else
        {
            btn_submit.Visible = true;
        }
    }

为什么返回空btn_submit 也等于true?

------解决方案--------------------
查询要用(int)cmd.ExecuteScalar()
C# code

private void _btn()
    {
        string sql = "select count(*) from [dhk_qiankuan] where user_name='" + ddl_name.SelectedItem.Text + "'";
        SqlConnection con = new SqlConnection(conString);
        con.Open();
        SqlCommand cmd = new SqlCommand(sql, con);
        int sum = (int)cmd.ExecuteScalar();
        if (sum == 0)
        {
            btn_submit.Visible = false;
        }
        else
        {
            btn_submit.Visible = true;
        }
    }

------解决方案--------------------
int sum = (int)cmd.ExecuteNonQuery();换成
int sum = (int)cmd.ExecuteScalar();
------解决方案--------------------
ExecuteNonQuery不是用了执行select语句的,你用ExecuteScalar得到count值来判断
------解决方案--------------------
ExecuteNonQuery 返回的是受影响的行数.