SQL Server:转换为准备好的语句

时间:2018-09-14 02:33:05

标签: c# sql-server prepared-statement

以下代码容易受到SQL注入的影响,我正在尝试更正以前开发人员的代码;他使用DataTable来进一步使用查询-如何与数据表一起使用prepare语句?

string data = "";
int i = 1;

cmd = new SqlCommand("select * from maincategory where isactive=1 and id in (select catid from productmaster where isactive=1)", con);

con.Open();

DataTable dt = new DataTable();
dt.Load(cmd.ExecuteReader());
con.Close();

if (dt.Rows.Count > 0)
{
     data += "<ul>";

     foreach (DataRow DR in dt.Rows)
     {
         data += "<li><a href='product.aspx?cid="+DR["id"]+"'>" + DR["catname"] + "</a></li>";
     }

     data += " </ul>";
}

lblpartners.Text = data;

我尝试过的代码:

public void show()
{    
     string data = "";
     int i = 1;

     cmd = new SqlCommand("select * from maincategory where isactive=@val1 and id in (select catid from productmaster where isactive=@val2)", con);

     con.Open();
     cmd.Parameters.AddWithValue("@val1", 1);
     cmd.Parameters.AddWithValue("@val2", 1);

     DataTable dt = new DataTable();
     dt.Load(cmd.Prepare());
     con.Close();

     if (dt.Rows.Count > 0)
     {
        data += "<ul>";

        foreach (DataRow DR in dt.Rows)
        {
            data += "<li><a href='product.aspx?cid="+DR["id"]+"'>" + DR["catname"] + "</a></li>";
        }

        data += " </ul>";
    }

    lblpartners.Text = data;
}    

1 个答案:

答案 0 :(得分:0)

SqlCommand.Prepare不返回IDataReader it's a void methodDataReader.Load()需要一个IDataReader对象。

也许你是说dt.Load(cmd.ExecuteReader())