C#INSERT INTO Access数据库失败,没有给出任何错误



尝试将新记录插入MS Access.accdb文件。当我运行下面的代码时,它似乎工作得很好。没有出现任何错误,但数据库文件中也没有任何更新。我已验证数据库是否位于可访问的位置。

selectedNote是一个具有列出的三个参数的对象。查询字符串中唯一没有包含的字段是ID字段,它是自动编号。

string scon = "Provider = Microsoft.ACE.OLEDB.12.0; Data Source = |DataDirectory|AMS.accdb";
string str = "INSERT INTO Notes ([ItemID], [Note], [Note Date]) VALUES (?, ?, ?)";
try
{
using (OleDbConnection con = new OleDbConnection(scon))
{
using (OleDbCommand cmd = new OleDbCommand(str, con))
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("ItemID", selectedNote.ItemID);
cmd.Parameters.AddWithValue("Note", selectedNote.Note);
cmd.Parameters.AddWithValue("Note Date", selectedNote.NoteDate.ToString("dd-MM-yy"));
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
}
catch (Exception ex)
{
MessageBox.Show("Failed due to" + ex.Message);
}

谢谢大家,希望我能把它敲定。

编辑:奇怪的是,我刚刚发现,如果我用下面这样的行硬编码.accdb文件的路径,它实际上会写入该文件。所以我想问题变成了为什么它不在构建路径上工作,因为数据库与exe位于同一路径。

AppDomain.CurrentDomain.SetData("DataDirectory","C:temp");

我尝试过将DataDirectory设置为类似AppDomain.CurrentDomain.BaseDirectory的值,但这似乎也不起作用。

日期不应以文本形式插入,并且您有DateTime值,因此:

cmd.Parameters.AddWithValue("Note Date", selectedNote.NoteDate);

相关内容

最新更新