C# 尝试恢复数据库中某列的当前值时出错
我的表中有一列名为C# 尝试恢复数据库中某列的当前值时出错,c#,sql,C#,Sql,我的表中有一列名为AllowComent。此列具有位数据类型 在我的C代码中,我尝试恢复该值 protected string RecoverAllowComent(string id) { try { using(SqlConnection conexao = new SqlConnection(_conexao)) { SqlCommand comando = new SqlCommand();
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";
}
}
但是我弄错了
将nvarchar值“1”转换为数据类型int时,转换失败。
您正在传递具有类型字符串的id
。您需要将int
传递给参数
id
改变
comando.Parameters.Add(new SqlParameter("@Id", id));
到
如果可能,您可以将RecoverAllowComent的参数ID的类型更改为int,以避免将类型转换字符串更改为int。@Justiniessner ID为int为什么不更改comando.Parameters.Add(新的SqlParameter(“@ID”,ID));到comando.Parameters.AddWithValue(“@Id”,Id)//假设id为IntType,确保id声明为整数。您可以说明如何声明id以及在何处声明id吗?表的id列是什么类型,以及C#中id变量的数据类型?另外,如果结果是一行一列,请使用。还可以将方法签名从受保护的字符串RecoverAllowComent(字符串id)更改为受保护的bool RecoverAllowComent(字符串id),然后将返回类型更改为true catch return false;这里的颜色让我有点疯狂,但是如果
id
是数据库中的int
,为什么这个方法将它作为字符串
参数?它并没有“严格”地处理它,所以为什么不将它作为int
传递进来呢?如果需要,让调用代码转换它。@Adil我更新我的问题,现在我们可以看到,我的方法以字符串形式接收ID。yetI已经更新了我的答案数据库表中的ID类型是什么?在我的数据库中,ID是int数据类型。如果可能,可以将RecoverAllowComent的参数ID的类型改为int,以避免将字符串类型转换为int。如果是1,请尝试使用ExecuteScalar
行,返回1列。
comando.Parameters.Add(new SqlParameter("@Id", int.Parse(id)));