情况1:我无法将数据插入数据库
Dim conn As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|ProjectVB.accdb")
案例 2:我可以将数据插入数据库
Dim conn As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:UsersAdminDocumentsProjectVB.accdb")
数据库已保存在我的项目中
conn.Open()
cmd.Connection = conn
cmd.Parameters.AddWithValue("@ac_ID", txtID.Text)
cmd.Parameters.AddWithValue("@ac_pass", txtPassword.Text)
cmd.Parameters.AddWithValue("@nation_ID", txtNoID.Text)
cmd.Parameters.AddWithValue("@fName", txtFirstName.Text)
cmd.Parameters.AddWithValue("@lName", txtLastName.Text)
cmd.Parameters.AddWithValue("@tel", txtTel.Text)
cmd.Parameters.AddWithValue("@province", cbNation.SelectedItem)
cmd.Parameters.AddWithValue("@regOn", dtRegOn.Text)
cmd.Parameters.AddWithValue("@status", txtStatus.Text)
cmd.Parameters.AddWithValue("@gender", cbGender.SelectedItem)
cmd.Parameters.AddWithValue("@location", txtLocation.Text)
cmd.Parameters.AddWithValue("@img", imgBuffer)
cmd.Parameters.AddWithValue("@rank", cbRank.SelectedItem)
cmd.CommandText = "INSERT INTO db_KJ_Profile VALUES(@ac_ID,@ac_pass,@nation_ID,@fName,@lName,@tel,@province,@regOn,@status,@gender,@location,@img,@rank)"
cmd.ExecuteNonQuery()
对于 DataDirectory 替换字符串,您应该检查文件夹PROJECTFOLDERBINDEBUG
(或相同路径的 x86 版本)中数据库的内容。
这是因为在 WinForms 应用程序中,在 VS 的调试会话中运行时,DataDirectory
指向执行应用程序的文件夹(项目文件夹的 BIN\DEBUG 或 BIN\x86\DEBUG 子文件夹)。
这很容易被忽视,它总是令人困惑的根源。
如果您在项目项中列出了 ACCDB 文件,情况会更糟。在这种情况下,数据库项具有一个名为 Copy To The Output Directory
的属性。您应该检查是否设置为 Copy If Newer or Copy Never
而不是 Copy Always
,因为在这种情况下,每次重新启动调试会话时,都会将数据库的新副本(当然没有刚刚插入的数据)从项目文件夹复制到 BIN\DEBUG 文件夹