md.CommandText = "select * from HFour where ID=" + id[num];
SqlDataReader re = cmd.ExecuteReader();
if (re.HasRows)
{
while (re.Read())
{
oldvalue.ID = Convert.ToInt32(re[0]);
oldvalue.Name = re[1].ToString();
oldvalue.Description = re[2].ToString();
oldvalue.SourceID = re[3].ToString();
if (re[4] !=DBNull.Value)
{
oldvalue.SourceTypeID = Convert.ToInt32(re[4]);
}
else
{
}
oldvalue.CreatedOn = Convert.ToDateTime(re[5]);
oldvalue.CreatedBy = re[6].ToString();
if (re[7] != DBNull.Value)
{
oldvalue.ModifiedOn = Convert.ToDateTime(re[7]);
}
oldvalue.ModifiedBy = re[8].ToString();
oldvalue.HThreeID = Convert.ToInt32(re[9].ToString());
oldvalue.IsActive = Convert.ToBoolean(re[10].ToString());
}
re.Close();
string command = "update HFour set Name='" + oldvalue.Name + "'," +
"Description='" + oldvalue.Description + "'," +
"SourceID='" + oldvalue.SourceID + "'," + "SourceTypeID=" +
oldvalue.SourceTypeID + "," + "CreatedOn='" +
oldvalue.CreatedOn + "'," + "CreatedBy='" +
oldvalue.CreatedBy + "'," + "ModifiedBy='" +
oldvalue.ModifiedBy + "'," + "ModifiedOn='" +
oldvalue.ModifiedOn + "'," + "HThreeID=" +
oldvalue.HThreeID + "," + "IsActive='" +
oldvalue.IsActive + "' where ID=" + id[num];
cmd.CommandText = command;
int reed = cmd.ExecuteNonQuery();
,错误如下:
类型' System.Data.SqlClient.SqlException'的异常发生在 System.Data.dll但未在用户代码中处理
其他信息:
','
附近的语法不正确
任何建议都会非常感谢
答案 0 :(得分:3)
问题在于您构建的命令。它形成得不好。
然而,此代码存在更严重的问题。它容易受到SQL injection的攻击。您必须构建一个参数化查询,以避免它,如下所示:
string command = "UPDATE HFour SET Name=@Name, Description=@Description";
command.Parameters.Add(new SqlParamter("@Name",oldvalue.Name));
command.Parameters.Add(new SqlParamter("@Description",oldvalue.Description));
显然,第一个sql查询也是如此。
"select * from HFour where ID=" + id[num];
您还必须将此参数化查询。