首页 > 解决方案 > SQL Server INSERT 语句未执行,但我也没有收到异常

问题描述

在我的按钮单击事件中,我想在表格中插入一行。当我单击按钮时,我没有例外,我也没有显示我的消息框。我有消息框作为检查查询是否已执行的一种方式。

当我单步执行时,它会跳过 MessageBox 并且不会引发异常。

private void BtnSend_Click(object sender, EventArgs e)
{
    string theDate = dateTimePicker1.Value.ToString("MM-dd-yyyy");

    var select = "INSERT INTO Trinity3(Date, Device_S_N, Student_Last_Name, Student_First_Name, Student_Number, School, Grade, Damage)" +
                 "VALUES (@Date, @Serial, @LastName, @FirstName, @StudentNum, @School, @Grade, @Damage)" +
                 "COMMIT";

    SqlConnection connection = new SqlConnection("Data Source=CPS1113020004; Initial Catalog=Coweta Public Schools; Integrated Security=True");               

    // Create a SqlCommand instance
    SqlCommand command = new SqlCommand(select, connection);

    // Add the parameter
    command.CommandType = CommandType.Text;
    command.CommandText = select;
    command.Parameters.AddWithValue("@Date", theDate);
    command.Parameters.AddWithValue("@Serial",txtSerial.Text);
    command.Parameters.AddWithValue("@LastName",txtLastName.Text);
    command.Parameters.AddWithValue("@FirstName",txtFirstName.Text);
    command.Parameters.AddWithValue("@StudentNum", txtStudentNum.Text);
    command.Parameters.AddWithValue("@School",txtSchool.Text);
    command.Parameters.AddWithValue("@Grade", txtGrade.Text);
    command.Parameters.AddWithValue("@Damage", txtDamage.Text);

    // Execute the query
    try
    {
        connection.Open();
        command.ExecuteNonQuery();
        MessageBox.Show("Records inserted successfully");
    }
    catch
    {
        // Handle exception, show message to user...
    }
    finally
    {
        connection.Close();
    }

    this.Visible = false;

    var searchForm = new SearchForm();
    searchForm.ShowDialog();
}

标签: c#sql-serverwinforms

解决方案


您正在抛出异常,但您没有看到,因为您的 catch 块中没有任何内容。

  1. 查找 Try with Resources 约定并始终使用它。即使出现异常,这也会自动为您关闭连接。这是必须的。

  2. 向您的 catch 块添加一个异常,以便您可以看到错误。

  3. 您的 SQL 字符串需要在每个部分之后有空格。当您使用“+”连接时,不会创建额外的空间。所以你的查询实际上是这样的: INSERT INTO Trinity3(Date, Device_S_N, Student_Last_Name, Student_First_Name, Student_Number, School, Grade, Damage)VALUES (@Date, @Serial, @LastName, @FirstName, @StudentNum, @School, @Grade, @Damage)COMMIT

  4. 与其在应用程序中编写查询,不如在数据库中创建一个存储过程,其中包含获取数据所需的所有逻辑。然后您的应用程序将简单地调用一个单词存储过程,而不是使用一个代表您的 t-sql 的巨大字符串。您还可以实际测试您的存储过程并确保它在不涉及应用程序的情况下工作。


推荐阅读