如何在动态sql中传递列作为参数 - C#,sql server compact

时间:2014-12-14 09:30:08

标签: c# sql-server-ce sql-injection dynamic-sql string.format

此问题是我问Here

的另一个问题

我有一个win形式,里面有复选框控件。复选框的名称与表的列名匹配。我无法规范表格所涉及的大量数据的原因,已经收到了实时项目。所以一切都保持不变。 我将选定的checbox名称作为csv col1,col2,col3,后来我将它连接到sql string。(没有SP作为sql compact 3.5 sdf dbase)。 在我的DataAccess类的GetData()方法中,我形成了sql字符串。但是为了避免sql注入,如何确保传递的列名称得到验证。



//  Get Data
// selectedMPs: string csv, generated from the list of selected posts(checkboxes) from the UI, forming the col names in select
public static DataTable GetDataPostsCars(string selectedMPs, DateTime fromDateTime, DateTime toDateTime)
{
  DataTable dt;
  //string[] cols = selectedMPs.Split(','); //converts to array
  //object[] cols2 = cols;//gets as object array            
  //=== using cols or cols 2 in String.Format does not help

  // this WORKS, but as i am aware its prone to injections. so how can i validate the "selectedMPs" that those are columns from a list or dictionary or so on? i am not experienced with that.

  string sql = string.Format(
            "SELECT " + selectedMPs + " " +
            "FROM GdRateFixedPosts " +
            "WHERE MonitorDateTime BETWEEN '" + fromDateTime + "' AND '" + toDateTime +
  using (cmd = new SqlCeCommand(sql,conn))
  {
    cmd.CommandType = CommandType.Text;                //cmd.Parameters.Add("@toDateTime",DbType.DateTime);
    dt = ExecuteSelectCommand(cmd);
  }
  return dt;
}




这项工作,但我知道它容易注射。那么如何验证" selectedMPs"那些是列表或字典中的列等等?我没有经验。我将衷心感谢您的帮助。提前谢谢。

1 个答案:

答案 0 :(得分:1)

这是唯一可能的方法,并且没有SQL Server Compact注入的风险,因为该数据库引擎每批只执行一个语句。