带有 Access 数据库 (accdb) 的 c# windows 应用程序在安装后无法在其他计算机上运行

The c# windows app with Access database (accdb) doesn't work on other computers after installation

我想在 C#-windows 应用程序项目中的 Access 数据库 (accdb) 中插入文本。 "accdb" 。 只有当我 运行 位于我的项目源文件夹中的 exe 文件时,它才能在我的计算机上正常工作,但问题是当我构建安装文件并安装它和 运行 软件时,它会打开但是当我点击插入按钮时,它无法工作。问题出在数据库 (location/access) 上,但我不知道该如何解决。 有谁知道如何解决这个问题?

错误是:您的应用程序中发生了未处理的异常。 ...“您的应用程序中发生了未处理的异常。如果您单击继续,应用程序将忽略此错误并尝试继续。如果您单击退出,应用程序将立即关闭。 有关调用的详细信息,请参阅此消息的末尾 实时 (JIT) 调试而不是此对话框。

************** 异常文本 ************** System.Data.OleDb.OleDbException (0x80004005):操作 muss eine aktualisierbare Abfrage verwenden。 在 System.Data.OleDb.OleDbCommand.ExecuteCommandTextErrorHandling(OleDbHResult 小时) 在 System.Data.OleDb.OleDbCommand.ExecuteCommandTextForSingleResult(tagDBPARAMS dbParams, Object& executeResult) 在 System.Data.OleDb.OleDbCommand.ExecuteCommandText(对象和执行结果) 在 System.Data.OleDb.OleDbCommand.ExecuteCommand(CommandBehavior 行为,Object& executeResult)

这是我的代码:

 public Form1()
    {
        InitializeComponent();
    }

    public static string GetDBConnection()
    {
        try
        {
            string dbExecPath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "Test11.accdb");
            return $"Provider=Microsoft.ACE.OLEDB.12.0;Data Source={ dbExecPath }";
        }
        catch (Exception)
        {
            return string.Empty;
        }
    }

   OleDbConnection con = new OleDbConnection(GetDBConnection());
   OleDbCommand cmd;

    private void button1_Click(object sender, EventArgs e)
    {

        OleDbCommand cmd = new OleDbCommand("insert into[Table](name, code) VALUES(@name, @code)", con);
            cmd.CommandType = CommandType.Text;

            cmd.Parameters.AddWithValue("@name", textBox1.Text);
             cmd.Parameters.AddWithValue("@code", textBox2.Text);

            con.Open();

            System.Windows.Forms.MessageBox.Show("An Item has been successfully added", "Caption", MessageBoxButtons.OKCancel, MessageBoxIcon.Information);

        int i = 0;
        i = cmd.ExecuteNonQuery();
        if (i > 0)
        {
            MessageBox.Show("Inserted");
            DisplayData();
        }

        else
        {
            MessageBox.Show("Not Inserted");
        }
        con.Close();
        ///////
    }

在您的代码中,您使用 Assembly.getExecutingAssembly().Location 指定 .accdb 文件的位置。一旦更改可执行文件 (.exe) 的位置,Assembly.getExecutingAssembly().Location returns 的值就会更改 (See MS docs)。因此,您需要确保您的可执行文件和 .accdb 文件始终位于同一文件夹中。否则无法与您的 Access 数据库建立连接。

您可以添加一个消息框,显示您的程序期望数据库所在的路径。之后您可以检查您的数据库是否真的位于正确的目录中。