Sql asp.net 中与 DataSet 相关的异常

Sql Exception related to DataSet in asp.net

我想在我的 "Service Fees" table 中获取 id 指定行的值。当我尝试执行以下代码时出现异常,显示 "An exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll but was not handled in user code.Additional information: Incorrect syntax near 'a34'."

是关于数据集对象吗?

PS:id为; ee83089d-4a34-46e0-be6c-b8b506f31a8e

 if (Request.QueryString["MyId"] != null)
            {
                isUpdate = true;
                var id = Request.QueryString["MyId"].ToString();

                SqlCommand cmd2 = new SqlCommand("SELECT * FROM ServiceFees WHERE Id=" + id, connection);
                SqlDataAdapter adapter2 = new SqlDataAdapter(cmd2);

                DataSet ds = new DataSet();
                adapter2.Fill(ds);

                sf1.name = ds.Tables[0].Rows[0][1].ToString();

            }

用单引号将您的 ID 括起来,它应该类似于:

 SqlCommand cmd2 = new SqlCommand("SELECT * FROM ServiceFees WHERE Id='" + id +"'", connection);

Id 是 GUID,应该用单引号括起来。

您将未加引号的 ID 传递给 SQL。

因此,它可能正在尝试计算 ee83089d-4a34-46e0-be6c-b8b506f31a8e 的结果。

你可能想要:

SqlCommand cmd2 = new SqlCommand("SELECT * FROM ServiceFees WHERE Id='" + 
  id + "'", connection);

或其他一些不易受到注入攻击的 SQL 调用。

SqlCommand cmd2 = new SqlCommand("SELECT * FROM ServiceFees WHERE Id= @id", connection);
cmd2.Parameters.Add(new SqlParameter("id",id));

避免sql注入。

谨防SQL注入

不要用单引号,双引号传递参数

始终使用 SqlParameter Class

因为您的参数是字符串,您需要将其作为 string 数据类型

传递
string Id="ee83089d-4a34-46e0-be6c-b8b506f31a8e";
    SqlParameter para1=new SqlParameter("@Id",SqlDbType.Varchar,500);
    para1.Value=Id;
    SqlCommand cmd2 = new SqlCommand("SELECT * FROM ServiceFees WHERE Id=@Id" , connection);
cmd2.Parameters.Add(para1);

SqlDataAdapter adapter2 = new SqlDataAdapter(cmd2);