字符串或二进制数据将在cmd.ExecuteNonQuery()上截断

时间:2013-09-14 08:19:53

标签: c# sql-server

执行项目时出错。我在这个按钮中有两个命令。有人可以帮我弄这个吗?我无法发现问题。它之前工作正常,但现在它出现了问题。我正在开发一个图书馆系统

SqlCommand cmd = con.CreateCommand();
cmd.CommandText = "INSERT INTO Borrowbook ([Student ID], ISBN, Title, Date, [Due Date]) VALUES (@StudentID, @ISBN, @Title, @Date, @DueDate)";
Control[] controls = { textBox2, textBox3, textBox4 };

foreach (Control c in controls)
{
   if (c.Text.Trim() == "")
   {
      MessageBox.Show("Please complete the fields", "Information...",
                      MessageBoxButtons.OK, MessageBoxIcon.Warning,
                      MessageBoxDefaultButton.Button1);
      return;
   }
}

SqlParameter p1 = new SqlParameter("@StudentID", SqlDbType.NChar);
p1.Value = textBox2.Text;
cmd.Parameters.Add(p1);

SqlParameter p2 = new SqlParameter("@ISBN", SqlDbType.NVarChar);
p2.Value = textBox4.Text;
cmd.Parameters.Add(p2);

SqlParameter p3 = new SqlParameter("@Title", SqlDbType.VarChar);
p3.Value = textBox3.Text;
cmd.Parameters.Add(p3);

SqlParameter p4 = new SqlParameter("@Date", SqlDbType.DateTime);
p4.Value = dateTimePicker1.Text;
cmd.Parameters.Add(p4);

SqlParameter p5 = new SqlParameter("@DueDate", SqlDbType.DateTime);
p5.Value = duedate.Text;
cmd.Parameters.Add(p5);

cmd.ExecuteNonQuery();

cmd.CommandText = ("UPDATE Books SET Availability = 'Borrowed' WHERE ISBN = '" + textBox4.Text + "'");
cmd.ExecuteNonQuery();

cmd.CommandText = ("INSERT INTO Penalty([Student ID], Title, [Date Borrow], [Due Date]) VALUES  (@StudentID1, @Title1, @Date1, @Date2)");

SqlParameter pp1 = new SqlParameter("@StudentID1", SqlDbType.VarChar);
pp1.Value=textBox2.Text;
cmd.Parameters.Add(pp1);

SqlParameter pp3 = new SqlParameter("@Title1", SqlDbType.NVarChar);
pp3.Value = textBox3.Text;
cmd.Parameters.Add(pp3);

SqlParameter pp4 = new SqlParameter("@Date1", SqlDbType.DateTime);
pp4.Value = dateTimePicker1.Text;
cmd.Parameters.Add(pp4);

SqlParameter pp5 = new SqlParameter("@Date2",SqlDbType.DateTime);
pp5.Value=duedate.Text;
cmd.Parameters.Add(pp5);

cmd.ExecuteNonQuery();
MessageBox.Show("The books has been successfully borrowed!", "Information ... ", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1);

2 个答案:

答案 0 :(得分:2)

首先:这个错误究竟发生在哪里?您的代码中有多个命令 - 哪一个导致错误?

其次:错误很明显:您尝试存储的至少一个值太长。因此,您可能在数据库中定义了Varchar(20),并且您尝试存储长度为25个字符的字符串。

找到这个问题,修复它。要么使数据库列更长(例如将其长度增加到25个字符),要么缩短您要插入该列的字符串以遵守定义的最大长度。

不幸的是,SQL Server并没有真正帮助您找出哪个参数是问题 - 您必须自己进行调试&看哪些太长了。

答案 1 :(得分:0)

cmd.ExecuteNonQuery();
MessageBox.Show("The books has been successfully borrowed!", "Information ... ",MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1);

感兴趣的是,您如何知道“已成功借阅图书” - 您没有处理执行命令时可能产生的任何错误。