【问题标题】:ERROR: Index (zero based) must be greater than or equal to zero and less than the size of the argument list错误:索引(从零开始)必须大于或等于零且小于参数列表的大小
【发布时间】:2011-11-20 06:05:55
【问题描述】:

我正在尝试将数据插入到我的数据库中,命令如下:

 public static bool InsertUser(string Date, string Day, string HourFrom, string HourTo, int HoursWorked, int Where)
    {
    string sql = string.Format("INSERT INTO Tablee (Date, Day, HourFrom, HourTo, HoursWorked, Where)VALUES('{0}','{1}','{2}','{3}','{4}',{5},{6})", Date, Day, HourFrom, HourTo, HoursWorked, Where);

    return DAL.ExecuteNonQuery(sql) != 0;
}

现在我收到了我在主题中写的错误,它来自我构建 String Sql 的行(“INSERT INTO ...”)。任何人都知道我该如何解决它?

附: '{0}'.'{1}'.. 的用途是什么?我从我做的一个旧项目中复制了它,我不记得它为什么在那里以及它做了什么。

【问题讨论】:

  • 避免通过连接或格式化字符串来创建查询。改为使用参数。
  • 别忘了评论你的代码;它可能有助于将来避免这个问题(“P.S. Just Cause...”)。
  • string.Format("format string", ) 将用第 N 个格式参数替换 {N} 模式,从 0 开始计数。 string.Format("{0} {1} !", "Hello", "world") 将 {0} 替换为 Hello 并将 {1} 替换为 world 返回 "Hello world!"结果是字符串。

标签: c# sql database


【解决方案1】:

您列出了 7 个 个索引 (0-6),并且只有 6 个参数。

删除{6}

【讨论】:

    【解决方案2】:

    有这个电话:

    string.Format("...{0}','{1}','{2}','{3}','{4}',{5},{6}...", parameters...);
    

    您应该提供 7 个参数,从 0 到 6,目前您只提供 6 个:

    Date, Day, HourFrom, HourTo, HoursWorked, Where
    

    这就是错误。

    【讨论】:

      【解决方案3】:

      一些创意格式说明了您的问题:

      VALUES(
      '{0}',   '{1}',   '{2}',      '{3}',    '{4}',         {5},      {6})"
      Date,    Day,     HourFrom,   HourTo,   HoursWorked,   Where           <<whoops
      

      要么删除“6”,要么为其提供一个值。

      【讨论】:

        猜你喜欢
        • 2011-04-18
        • 2011-12-19
        • 2016-07-03
        • 2023-04-11
        • 2016-04-01
        • 2018-07-26
        • 1970-01-01
        • 2012-04-07
        相关资源
        最近更新 更多