【问题标题】:[C#]Doesn't insert in DB, does give a executenonquery of 1[C#]不插入数据库,执行非查询为 1
【发布时间】:2013-05-14 01:27:04
【问题描述】:

我正忙于一个项目,我必须在一个紧凑的 SQL db 文件中插入一些数据,该文件是在 Visual Studio 2010 express 中创建的。我所做的每一次检查都表明插入操作正确,只有一个缺点,每次我检查数据库时都没有插入数据。 我试过了:

检查 command.executenonquery() 结果

我试过了。

我做了一个直接的 SQL 插入,并且成功了。

我检查了连接状态。

所以我没有想法,希望你们能帮忙。

哦,代码可能有用:

    private void butAddOilBlend_Click(object sender, EventArgs e)
    {
        ConnectToDB Connection = new ConnectToDB();
        try
        {
            Connection.Connect.Open();

            string SQLCommand = "INSERT INTO OilBlendsTable(oilblendsName, oilblendsDescription) VALUES(@OilBlendsName, @OilBlendsDescription)";

            using (SqlCeCommand Command = new SqlCeCommand(SQLCommand, Connection.Connect))
            {
                Command.Parameters.AddWithValue("@OilBlendsName", tbNameOilBlend.Text);
                Command.Parameters.AddWithValue("@OilBlendsDescription", tbOilBlendDescription.Text);

                Command.ExecuteNonQuery();
                int AffectedRows = Command.ExecuteNonQuery();

                MessageBox.Show(AffectedRows.ToString());
            }

            lblFinalWord.Text = "You just added a new blend named: " + tbNameOilBlend.Text;
        }
        catch (SqlException ex)
        {
            MessageBox.Show(ex.Message.ToString());
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message.ToString());
        }
        finally
        {
            Connection.Connect.Close();
        }
    }

【问题讨论】:

  • 您的连接字符串是否包含AttachDbFilename
  • 您的代码是正确的(不包括对 ExecuteNonQuery 的双重调用,但我认为这是您尝试的剩余部分)。您确定您正在检查插入使用的确切数据库吗?您的项目文件中是否列出了将属性复制到目标目录设置为始终复制并且您的连接字符串指向 |DataDirectory| 的数据库文件?
  • 请查看 IDisposable 以及 using 语句和连接池。
  • 我只是将 Cop 设置为 Destination 以始终复制,我将在此处放置我的 conn 字符串的副本:Data Source=|DataDirectory|\OilDB.sdf;Password=(Secret);Persist Security Info=True 我相信它是好的。我的连接字符串不包含 AttachDbFilename,我从来没有听说过。我马上谷歌一下。

标签: c# sql error-handling insert


【解决方案1】:

Copy Always 表示每次您开始调试应用程序时,都会将 SDF 文件的新副本从 Project Directory 复制到 DataDirectory,并覆盖已经存在的文件。

winforms 应用程序中的DataDirectory 是 BIN\DEBUG。
您的插入将进入该数据库 (BIN\DEBUG\OilDB.sdf)。
在下一次运行时,这些插入将丢失。
你应该使用Copy If Newer

Where is the |DataDirectory|
Visual Studio - File Properties

在这里,我假设您通过服务器资源管理器窗口中定义的连接查看存储在项目目录中的文件来检查丢失的数据。检查它的连接字符串

【讨论】:

  • 很高兴,是服务器资源管理器连接吗?
猜你喜欢
  • 2013-04-15
  • 1970-01-01
  • 2012-12-17
  • 2017-01-29
  • 1970-01-01
  • 2022-07-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多