【问题标题】:How to pass columns as parameters in dynamic sql - C#, sql server compact如何在动态 sql 中将列作为参数传递 - C#、sql server compact
【发布时间】:2014-12-14 09:30:07
【问题描述】:

这个问题是我问过的另一个问题的延伸Here

我有一个包含复选框控件的获胜表单。复选框的名称与表的列名匹配。由于涉及的大量数据,我无法规范化表格,这些数据已经为现场项目收到。所以一切都保持原样。 我将选定的复选框名称作为 csv col1、col2、col3 获得,稍后我将其连接到 sql 字符串。(没有 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”?我对此没有经验。我将衷心感谢您的帮助。提前致谢。

【问题讨论】:

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


    【解决方案1】:

    这是唯一可能的方法,并且不存在使用 SQL Server Compact 进行注入的风险,因为该数据库引擎每批只执行一条语句。

    【讨论】:

    • 嗨,埃里克!您能否详细说明一些参考资源?我用额外的 2 个参数 fromDateTime 和 ToDateTime 编辑了我的原始代码。如果不是完全没有必要,这些输入参数不应该从 C# 代码本身验证(通过数据库中的名称、类型等)吗?
    • 对于那些额外的参数,使用参数化的sql。
    • 当然。有道理。
    猜你喜欢
    • 1970-01-01
    • 2023-03-21
    • 1970-01-01
    • 2016-04-16
    • 1970-01-01
    • 1970-01-01
    • 2012-02-14
    • 2012-02-23
    • 2010-12-09
    相关资源
    最近更新 更多