Access 不会保存输入

Access won't save input

我查看了 Yt、Google 等。我尝试了 5 种解决方案,但没有任何效果。我把txt放到文本框,它显示在列表框中,但不要去访问。

简而言之。

 private void addAF_Click(object sender, EventArgs e)
    {


         if (aFInput.Text != "") {

            string q = "insert into AFs (AFNumber,SendDate,Notes) values ('"+aFInput.Text.ToString()+"','"+DateTime.Now+"', '"+notes.Text.ToString()+"')";
            dosomemagic(q);
            aFInput.Text = null;

        }

    }
    private void dosomemagic(String q)
    {

        try
        {
            cnn.Open();
            cmd.CommandText = q;
            cmd.ExecuteNonQuery();
            cnn.Close();
            loaddata();
        }
        catch (Exception e)
        {
            cnn.Close();
            MessageBox.Show(e.Message.ToString());
        }
    }

    private void ANLPA_Load(object sender, EventArgs e)
    {

        cnn.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=AFdbB03.mdb;";
        cmd.Connection = cnn;
        loaddata();
    }

    private void loaddata()
    {
        AFList.Items.Clear();
        try
        {
            string q = "select * from AFs";
            cmd.CommandText = q;
            cnn.Open();
            dr = cmd.ExecuteReader();
            if (dr.HasRows)
            {
                while (dr.Read())
                {
                    AFList.Items.Add(dr[1].ToString());
                    keyList.Items.Add(dr[0].ToString());

                }
            }
            dr.Close();
            cnn.Close();
        }
        catch (Exception ex) 
        {
            cnn.Close();
            MessageBox.Show(ex.Message.ToString());
        }
    }

当您的应用 运行 时,它 运行 来自文件夹 BIN\DEBUG 并且您将记录添加到 Visual Studio 复制到该文件夹​​的数据库中,当您开始调试会话。如果您的文件将 属性 Copy to Output Directory 设置为 Copy Always,则每次启动调试会话时,Visual Studio 将 MDB 文件从您的项目文件夹复制到您的输出目录(BIN\DEBUG 或 x86 变体)

这样,你的代码写对了,但是在下一个运行你的数据消失了,因为文件已经被Visual Studio

替代了

将 属性 Copy To Output directory 设置为 Copy NeverCopy if Newer

附带说明一下,请花点时间学习如何使用 parameterized query. Your code actually works, but what happen if your notes textbox contains a single quote in its Text property? The code will crash with a syntax error. But this is the minor of your problems. There is a well know hacking technique called Sql Injection,这可能会破坏数据库中的数据。