【问题标题】:ASP.net c# simple query paramter questionASP.net c#简单查询参数问题
【发布时间】:2011-01-28 16:57:14
【问题描述】:
        // Add into DB
        using (tblArtworkTemplatesTableAdapter tblAdapter = new tblArtworkTemplatesTableAdapter())
        {
            tblAdapter.Insert(DateTime.Now, "@specID");
            "@specID" = int.Parse(lstChooseSpec.SelectedValue)
        }

我知道代码是错误的,只是为了说明我的目标,我该如何参数化输入?

【问题讨论】:

    标签: c# asp.net parameters parameter-passing


    【解决方案1】:

    通常取决于。如果您使用任何类型的 ORM,如 LINQ to SQL 或 NHibernate,它会为您完成,无需任何问题。如果你使用普通 ADO 对象(我想是这种情况)来做这件事,那么你将不得不提出 Command(或 SQLCommand 或任何其他 ICommand 实现)对象并使用 SQLParameter 类(或其他参数类)。

    ICommand 具有您可以任意编辑的参数集合。

        SqlCommand cmd = new SqlCommand(
                "select * from STH where column = @SpecID", conn);
    
        //it might be useful to specify a type as well
        SqlParameter param  = new SqlParameter();
        param.ParameterName = "@SpecID";
        //I woudl use the TryParse method though
        param.Value         = int.Parse(lstChooseSpec.SelectedValue);
    
        cmd.Parameters.Add(param);
    

    【讨论】:

    • 我正在使用 DAL,我需要担心参数化输入还是它会为我做这件事?
    • 这取决于 DAL。我不知道 API。通常,DAL 会为您执行此操作,他们只需要传递常规 C# 数据值,并且他们自己关心参数化
    【解决方案2】:

    这一行

    "@specID" = int.Parse(lstChooseSpec.SelectedValue)
    

    不正确。您不能为常量赋值。您的意思可能类似于

    specId = int.Parse(lstChooseSpec.SelectedValue);
    

    其余代码令人困惑。为什么要将 lstChooseSpec.SelectedValue 解析为整数,然后尝试将其作为 DateTime 添加到适配器? C# 是强类型的:something 是 intDateTime,但不能同时是两者。

    如果您可以发布该方法的其余部分,这可能会有所帮助。

    Also, have a look at this overview on MSDN.

    【讨论】:

    • 我正在尝试插入两个值,第一个是 DateTime,第二个是整数。我想将插入查询的第二个输入作为参数以避免 SQL 注入
    猜你喜欢
    • 1970-01-01
    • 2018-04-24
    • 2021-08-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多