从数据库中删除

时间:2017-09-20 18:22:41

标签: database tsql executenonquery

我编写了一个从数据库中删除值的方法,但是当我检查受影响的行时,该值是0并继续进入第一个if语句中的任何想法?

     private void workstationDelete()
    {
        string query = "DELETE FROM test_revision2 where wsid = @wsid and location = '@location'";
        try
        {
            conn = new SqlConnection(connStr);
            conn.Open();

            SqlCommand cmd = new SqlCommand(query, conn);
            cmd.Parameters.AddWithValue("@wsid", Convert.ToInt32(wsid2text.Text));
            cmd.Parameters.AddWithValue("@location", deletelocation);
            cmd.ExecuteNonQuery();


            int rowsaffected = cmd.ExecuteNonQuery();

            if (rowsaffected == 0)
            {
                lblDel.Text = "Sorry Workstation: " + wsid2text.Text + " does not exist in " + deletelocation + ". Therefore it cannot be removed.";
            }
            else
            {
                lblDel.Text = "You have successfully removed Workstation: " + Convert.ToInt32(wsid2text.Text) + " in " + deletelocation;
            }

            conn.Close();

        }

        catch (SqlException)
        {
            lblDel.Text = "randome";
        }
    }

2 个答案:

答案 0 :(得分:0)

'@location'中删除单引号。你让它忽略了参数并尝试匹配字符串文字。

除此之外:good reasons不使用AddWithValue

答案 1 :(得分:0)

问题是我使用cmd.executeNonQuery两次,第一次返回1但是当我初始化为var时它变为0.使用执行非查询一次 - 当分配int var。