当我尝试恢复数据库中列的当前值时,出现错误

本文关键字:错误 恢复 数据库 | 更新日期: 2023-09-27 17:49:39

我的表中有一个名为AllowComent的列。该列具有位数据类型。

在我的c#代码中,我尝试恢复值
protected string RecoverAllowComent(string id)
{
    try
    {
        using(SqlConnection conexao = new SqlConnection(_conexao))
        {
            SqlCommand comando = new SqlCommand();
            comando.CommandText = "SELECT AllowComent FROM San_Blog WHERE Id = @Id";
            comando.Parameters.Add(new SqlParameter("@Id", id));
            comando.CommandType = CommandType.Text;
            comando.Connection = conexao;
            conexao.Open();
            comando.ExecuteNonQuery();
            SqlDataAdapter da = new SqlDataAdapter(comando);
            DataTable dt = new DataTable();
            da.Fill(dt);
            if (dt.Rows.Count > 0)
            {
                return dt.Rows[0].ItemArray[0].ToString();
            }
            else                    
                return "False";
         }
     }
     catch
     {
         return "False";
     }
}

但是我得到了错误Conversion failed when converting the nvarchar value ''1'' to data type int.

当我尝试恢复数据库中列的当前值时,出现错误

您正在传递类型为字符串的id。您需要将int传递给parameter id。

改变
comando.Parameters.Add(new SqlParameter("@Id", id));

comando.Parameters.Add(new SqlParameter("@Id", int.Parse(id)));

如果可能的话,您可以将recoverallowcomment的参数ID类型更改为int,以避免将类型转换为int。