在将 DateTime 参数类型传递给 DB 时使用 String.Format.引发异常.怎么了
本文关键字:Format String 怎么了 异常 类型 参数 DateTime DB 在将 | 更新日期: 2023-09-27 17:57:20
object args = new object[] { "Project", "ProjectName", "@PrName", "ProjectStartDate", "@StartDate", "ProjectEndDate", "@EndDate", "ProjectId", "@Id" };
//**此行导致引发异常 *****
string commandString = string.Format(@"UPDATE FROM {0} SET {1} = {2}, {3} = {4} , {5} = {6} WHERE {7} = {8}", args);
command.CommandText = commandString;
command.CommandType = CommandType.Text;
command.Connection = connection;
command.Parameters.Add("@Id", SqlDbType.Int).Value = selId;
command.Parameters.Add("@PrName", SqlDbType.Text).Value = projectName;
command.Parameters.Add("@StartDate", SqlDbType.DateTime).Value = startDate;
command.Parameters.Add("@EndDate", SqlDbType.DateTime).Value = endDate;
connection.Open();
int result = command.ExecuteNonQuery();
//
****** 异常详细信息 ********System.FormatException 未处理 消息=索引(从零开始)必须大于或等于零且小于参数列表的大小。 来源=mscorlib 堆栈跟踪: at System.Text.StringBuilder.AppendFormat(IFormatProvider provider, String format, Object[] args)
at System.String.Format(IFormatProvider provider, String format, Object[] args)
at System.String.Format(String format, Object arg0)
at DAL.DataAccess.UpdateRec(Int32 selId, String projectName, DateTime startDate, DateTime endDate) in 'Projects'Consulting'DAL'DataAccess.cs:line 106
at Consulting.frmProject.btnAdd_Click(Object sender, EventArgs e) in 'frmProject.cs:line 48
尝试下面的代码。它应该有效。
object[] args = new object[] { "Project", "ProjectName", "@PrName", "ProjectStartDate", "@StartDate", "ProjectEndDate", "@EndDate", "ProjectId", "@Id" };
如果有效,请标记为答案。