【问题标题】:String or binary data would be truncated.?字符串或二进制数据将被截断。?
【发布时间】:2012-08-20 21:51:06
【问题描述】:

我正在 C# Web 应用程序中构建输入表单。我可以很好地提交它,但我收到System.Data.SqlClient.SqlException (0x80131904): String or binary data would be truncated 错误。我知道这是一个长度问题,但我仔细检查了所有内容,但似乎无法在这里弄清楚。

{
    // Open Connection
    thisConnection.Open();

    // Create INSERT statement with named parameters
    nonqueryCommand.CommandText = "INSERT  INTO InventoryInput (Date, Item, Qty, WStatus) VALUES (@Date, @Qty, @Item, @WStatus)";


    // Add Parameters to Command Parameters collection
    nonqueryCommand.Parameters.Add("@Date", System.Data.SqlDbType.DateTime);
    nonqueryCommand.Parameters.Add("@Item", System.Data.SqlDbType.VarChar, 255);
    nonqueryCommand.Parameters.Add("@QTY", System.Data.SqlDbType.NChar, 10);
    nonqueryCommand.Parameters.Add("@WStatus", System.Data.SqlDbType.VarChar, 50);


    nonqueryCommand.Parameters["@Date"].Value = TextBox1.Text;
    nonqueryCommand.Parameters["@Item"].Value = DropDownList1.Text;
    nonqueryCommand.Parameters["@QTY"].Value = TextBox2.Text;
    nonqueryCommand.Parameters["@WStatus"].Value = DropDownList3.Text;
    nonqueryCommand.ExecuteNonQuery();

}

【问题讨论】:

  • (1) ID 是否自动递增? (2) 我相信你有一个错字。注意@Qty@QTY。 AFAIK 它区分大小写。
  • 那么,DropDownList1.TextTextBox2.Text 的长度是多少?和DropDownList3.Text?第一个 (TextBox1,Text) 更有趣。就个人而言,我认为您应该先进行显式解析,然后给它 DateTime,而不是字符串
  • 同样,您也不应该将数量保存为字符串 - 使用整数数据类型
  • @Andre 区分大小写取决于数据库设置和主数据库设置
  • @MarcGravell 确实,谢谢 Marc。

标签: c# sql-server


【解决方案1】:

您混淆了您的两列:

(Date,  Item, Qty,   WStatus) VALUES
(@Date, @Qty, @Item, @WStatus)

您正在尝试将您的 @Qty 插入到 Item 列(好的),并将 @Item 插入到 Qty 列(可能是错误的)。

我也同意 cmets 的观点,即某些数据类型看起来仍然可疑 - 例如一个非数字量。

【讨论】:

  • 很好看。那种很容易被忽视的错误。 :)
【解决方案2】:

使用Substring() 确保您的输入不会太长:

nonqueryCommand.Parameters["@Date"].Value = TextBox1.Text;
nonqueryCommand.Parameters["@Item"].Value = DropDownList1.Text.Substring(0, 255);
nonqueryCommand.Parameters["@QTY"].Value = TextBox2.Text.Substring(0, 10);
nonqueryCommand.Parameters["@WStatus"].Value = DropDownList3.Text.Substring(0, 50);

【讨论】:

  • 将它们放入指定长度的参数中,如果它们太长的话,会默默地截断它们,所以这不是解释。
  • @DanielA.White 绝对可以。该错误是因为发送到SqlCommand 的数据超出了列的容量。理想情况下,这将是客户端验证检查。
  • @DanielA.White:鉴于整个问题似乎是其中一个或多个问题太长,它似乎肯定会(至少在这里)。 :)
  • 如果字符串小于 X,Substring(0,X) 会抛出错误
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-10-21
  • 2022-01-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多