C# 为什么我的;插入“;没有插入数据库?

C# 为什么我的;插入“;没有插入数据库?,c#,sql,winforms,C#,Sql,Winforms,我在Visual Studio中使用C#开发了一个WinForms应用程序。当我运行以下代码时,它不会给出错误,但不会将任何数据插入到数据库表中 代码: 问题可能是什么?创建和使用ADO.NET SQL连接和命令的最新模式位于嵌套的using语句中,类似于以下内容: using (var connection = new SqlConnection(dbfile)) using(var command = connection.CreateCommand()) { connection.

我在Visual Studio中使用C#开发了一个WinForms应用程序。当我运行以下代码时,它不会给出错误,但不会将任何数据插入到数据库表中

代码:


问题可能是什么?

创建和使用ADO.NET SQL连接和命令的最新模式位于嵌套的using语句中,类似于以下内容:

using (var connection = new SqlConnection(dbfile))
using(var command = connection.CreateCommand())
{
    connection.Open();

    command.CommandText = "Insert into Temptranstion (CustomerID, ProductName,Quantity,Price,DateTime ) Values (@CustomerID,@ProductName,@Quantity,@Price,@DateTime)";
    command.Parameters.AddWithValue ("@CustomerID ",comboBox1.SelectedValue);
    command.Parameters.AddWithValue ("@ProductName",textBox6.Text);
    command.Parameters.AddWithValue ("@Quantity",textBox7.Text);
    command.Parameters.AddWithValue ("@Price",textBox8.Text);
    command.Parameters.AddWithValue ("@DateTime",DateTime.Now);
    command.ExecuteNonQuery();
}
请注意,我并没有运行这段代码,我只是以一种方式重构了您的代码,即无论发生什么情况,连接和命令始终是关闭和释放的

如果仍然无法在数据库中看到新记录,则可能是由于不同的故障点:

1) 您的连接字符串是什么样子的

2) 您是在检查正确的目标数据库,还是在每次执行时都重新部署了数据库

3) 输入参数中的值是什么

祝你好运


Davide.

我在您的代码中没有看到提交。提交后,也请关闭连接。这是一个愚蠢的问题,但检查简单的事情并没有坏处。您确定要根据连接字符串中的内容检查正确的数据库吗?+您可能需要使用“使用”语句。在桌面应用程序中,数据库文件将复制到
Bin/Debug
下,因此,我认为您应该将其查看到Bin/Debug/database文件中。
using (var connection = new SqlConnection(dbfile))
using(var command = connection.CreateCommand())
{
    connection.Open();

    command.CommandText = "Insert into Temptranstion (CustomerID, ProductName,Quantity,Price,DateTime ) Values (@CustomerID,@ProductName,@Quantity,@Price,@DateTime)";
    command.Parameters.AddWithValue ("@CustomerID ",comboBox1.SelectedValue);
    command.Parameters.AddWithValue ("@ProductName",textBox6.Text);
    command.Parameters.AddWithValue ("@Quantity",textBox7.Text);
    command.Parameters.AddWithValue ("@Price",textBox8.Text);
    command.Parameters.AddWithValue ("@DateTime",DateTime.Now);
    command.ExecuteNonQuery();
}