ExecuteNonQuery 正在运行,但更改未保存

ExecuteNonQuery is working but , changes are not saving

这是我正在处理的代码;

 public partial class Form2 : Form
{
    SqlConnection sc = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\Database1.mdf;Integrated Security=True");
    SqlDataAdapter sda;
    SqlCommand command;
    SqlCommand commands;
    public Form2()
    {
        InitializeComponent();
    }

    private void button2_Click(object sender, EventArgs e)
    {
        this.Close();
        Form1 f1 = new Form1();
        f1.Show();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        command = new SqlCommand(@"SELECT * FROM [Table] WHERE email='" + textBox4.Text + "'", sc);
        sda = new SqlDataAdapter(command);
        DataSet ds = new DataSet();
        sda.Fill(ds);
        int i = ds.Tables[0].Rows.Count;
        if (i == 1)

            MessageBox.Show("Email Already Taken");
        else
        {
            sc.Open();
            command = new SqlCommand("INSERT INTO [Table](name,surname,yearofbirth,adress_home_city,adress_home_block,adress_home_street,adress_work_city,adress_work_block,adress_work_street,email,password) VALUES('"+textBox1.Text+"','"+textBox2.Text+ "','" + textBox3.Text + "','" + textBox4.Text + "','" + textBox5.Text + "','" + textBox7.Text + "','" + textBox10.Text + "','" + textBox11.Text + "','" + textBox8.Text + "','" + textBox9.Text + "','" + textBox6.Text + "') ", sc);

            command.ExecuteNonQuery();
            sc.Close();
            MessageBox.Show("Success");

        }

它在我调试它时工作,它是一个注册表单,我可以使用我在此表单中提供的信息登录。

但是当关闭时,我执行的这个插入命令没有保存在我的数据库中。

// 附加信息;

在注册表格中时,我收到成功消息,如果我使用相同的信息重试,我收到电子邮件已被接收的消息

问题是因为您的 mdf 文件在重建时被空白文件替换,即每次重建应用程序时您的 mdf 文件都被复制到调试文件夹,因此删除了之前插入的所有数据。

解决方案

  1. 不要在解决方案中包含 mdf 文件。
  2. 在连接字符串中提供完整路径(如 AttachDbFilename=C:\Database1.mdf;)或 mdf 文件的相对路径

SqlConnection sc = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Database1.mdf;Integrated Security=True");

  1. 如果您将 mdf 文件包含到解决方案中,则将 属性 "Copy to Output Directory" 更改为 "Do not copy"
  2. 尽可能使用本地 MSSQL 服务器实例中的数据库,而不是指向 mdf 文件(MS SQLExpress 是免费的)。

仅当您从 visual studio 启动您的应用程序时才会发生此问题,如果您直接从 debug/release 文件夹多次启动该应用程序,该应用程序将正常工作,因为它没有被重建,并且所以mdf文件没有被替换。