2

I have an error while executing my project. I have two commands in this button. Can someone help me with this? I can't detect the problem. It is working fine before but now it occurred a problem. I'm developing an library system

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);
4

2 回答 2

3

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

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

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

不幸的是,SQL Server 并不能真正帮助您找出问题所在 - 您必须自己调试并查看哪些参数太长

于 2013-09-14T08:46:05.127 回答
0
cmd.ExecuteNonQuery();
MessageBox.Show("The books has been successfully borrowed!", "Information ... ",MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1);

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

于 2013-09-14T10:08:04.657 回答