ADO.NET:如何拥有N个参数?

时间:2010-10-08 02:17:20

标签: ado.net parameters

我需要将数据库中的一批行标记为“已处理”。

在过去,当事情变得更容易时,我会创建一些SQL:

UPDATE Readings SET IsProcessed = 1 WHERE ReadingDateTime IN (
    "2010-10-07 22:02:13.327",
    "2010-10-07 22:02:14.213",
    "2010-10-07 22:02:15.595",
    ...
    "2010-10-07 23:03:36.981")

循环查看日期列表:

sql = "UPDATE Readings SET IsProcessed = 1 WHERE ReadingDateTime IN (";
foreach (DateTime datetime in dates)
{
   sql = sql + CRLF+ DateTimeToSql(datetime)+",";
}
sql = sql+")";

并发出SQL:

ExecuteNonQuery(connection, sql);

一切都很好。

现在我想尝试以艰难的方式做事;我想尝试使用参数:

sql = ???;
command.CommandText = sql;

DbCommand command = connection.CreateCommand();
foreach (DateTime datetime in readings)
{
    command.Parameters.Add(new SqlParameter(???, SqlDbType.DateTime) {Value = datetime});
}
using (DbTransaction transaction = connection.BeginTransaction())
{
    command.Transaction = transaction;
    command.ExecuteNonQuery();
    transaction.Commit();
}

唯一的技巧是放入sql字符串,以及在参数循环的每次迭代中放入什么。他们需要一些名称。

命名任意数量参数的推荐方法是什么?

2 个答案:

答案 0 :(得分:1)

我认为你能做的就是这样: -

sql = "UPDATE Readings SET IsProcessed = 1 WHERE ReadingDateTime IN (";
for (int count=0; count<dates.Length; count++)
{
   sql = sql + CRLF + ":param" + count;
}
sql = sql+")";

for (int count=0; count<dates.Length; count++)
{
    command.Parameters.Add(new SqlParameter(":param" + count, SqlDbType.DateTime) {Value = datetime});
}

然而,我认为在这种情况下具体参数是不必要的。

考虑到您的动态值为dates而不是strings,您可以直接使用TryParse验证日期,以确保它们是正确的数据类型,然后再将它们附加到您的原始解决方案!!

我不知道你是否通过在这种情况下使用参数来实现额外的任何目标。

答案 1 :(得分:0)

您可以尽量减少:提供者将接受名为@0@1等的参数。但如果您想要更具描述性,只需使用{{1}的基本名称带有@ReadingDateTime的整数后缀。容易腻。