c# - 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();
}
解决方案
您正在抛出异常,但您没有看到,因为您的 catch 块中没有任何内容。
查找 Try with Resources 约定并始终使用它。即使出现异常,这也会自动为您关闭连接。这是必须的。
向您的 catch 块添加一个异常,以便您可以看到错误。
您的 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
与其在应用程序中编写查询,不如在数据库中创建一个存储过程,其中包含获取数据所需的所有逻辑。然后您的应用程序将简单地调用一个单词存储过程,而不是使用一个代表您的 t-sql 的巨大字符串。您还可以实际测试您的存储过程并确保它在不涉及应用程序的情况下工作。
推荐阅读
- python - 我将如何在 python 3.6 中解析这个 ret
- javascript - 将 JavaScript 数组转换为 formData
- exception - AVIOContext 读取回调中的异常处理
- javascript - 在 JavaScript 中按数组属性分组
- rest - 授权 REST 资源访问
- php - 如何将 php 文件相互交错并检查参数的 URL?
- c++ - C++ 客户端/服务器聊天应用程序 - 从 Ubuntu 命令窗口扫描输入
- mongodb - 仅将更改的值从表单提交更新到 MongoDB
- azure - Azure Devops 项目——它们来自哪里?如何去除?
- methods - V-for循环方法不直接导致渲染