因此,我一直在为客户端管理系统重构一些代码,以使用MS-Access而不是SQL Server,而且我觉得,就像我之前的问题一样,很可能是由于我不熟悉某些驾驶员/语言的怪癖,但我发现自己无论如何都在挣扎。从应用程序(cmd.ExecuteNonQuery()
调用Update语句时,我受到0行影响。将相同的字符串复制到Access查询中时,它将影响1行按预期方式。发生了什么事?
我尝试通过复制sql并将其直接插入Access中的新查询中来解决此问题,但是,它似乎按预期工作。在调试和检查命令/参数时,所有值似乎都正确传递,并且不会引发任何异常。该方法仅报告0行受到影响。
事件方法(点击运行)
private void BtSaveNotes_Click(object sender, EventArgs e)
{
int notesID;
string notes;
DateTime notesDate;
if (dgvCustomerNotes.SelectedRows.Count > 0
&& Int32.TryParse(dgvCustomerNotes.SelectedRows[0].Cells["CustomerNotes_ID"].Value.ToString(), out notesID))
{
if (!DateTime.TryParse(dgvCustomerNotes.SelectedRows[0].Cells["NotesDate"].Value.ToString(), out notesDate))
{
MessageBox.Show(
"There was an issue capturing the date as entered. Please try again.",
"Invalid Date",
MessageBoxButtons.OK,
MessageBoxIcon.Error);
return;
}
try
{
notes = dgvCustomerNotes.SelectedRows[0].Cells["Notes"].Value.ToString();
Customer.updateNotes(notesID, notes, notesDate);
MessageBox.Show(
"Successfully updated notes record.",
"Success",
MessageBoxButtons.OK,
MessageBoxIcon.Information);
}
catch (Exception ex)
{
MessageBox.Show(
$"There was an issue saving the record to the database!. \n\nException: {ex}",
"Data Access Failure",
MessageBoxButtons.OK,
MessageBoxIcon.Error);
Console.Error.WriteLine($"Error with data access!\n\n{ex}");
}
}
// TODO: Test this
//MessageBox.Show(
// "Sorry! That feature is not yet implemented.",
// "Not Implemented",
// MessageBoxButtons.OK,
// MessageBoxIcon.Warning);
}
调用实际更新的数据访问方法:
public static void updateNotes(int customerNotesID, string notes, DateTime notesDate)
{
string query = Scripts.sqlUpdateCustomerNotes;
using (
OleDbCommand dbCommand = new OleDbCommand()
{
Connection = new OleDbConnection(ConnectionAccess.connString),
CommandType = CommandType.Text,
CommandText = query,
Parameters =
{
new OleDbParameter("@CustomerNotes_ID", OleDbType.Integer),
new OleDbParameter("@Notes", OleDbType.LongVarChar),
new OleDbParameter("@NotesDate", OleDbType.Date) // captures date AND Time.
}
}) // end using parenthetical
{ // begin using scope
dbCommand.Parameters[0].Value = customerNotesID;
dbCommand.Parameters[1].Value = notes;
dbCommand.Parameters[2].Value = notesDate;
foreach (OleDbParameter param in dbCommand.Parameters)
{ // replace ambiguous null values with explicit DBNulls.
if (param.Value == null)
{
param.Value = DBNull.Value;
}
}
dbCommand.Connection.Open();
int rowsAffected = dbCommand.ExecuteNonQuery();
dbCommand.Connection.Close();
Console.WriteLine($"Rows affected: {rowsAffected}");
}
} // end updateCustomerNotes
从Scripts
类中获取的sql查询:
public static readonly string sqlUpdateCustomerNotes = "UPDATE CustomerNotes " +
"SET Notes = @Notes, NotesDate = @NotesDate WHERE CustomerNotes_ID = @CustomerNotes_ID";
运行时,查询字符串正确连接(认为可能是一个问题,但不是),参数已正确捕获/存储,并且没有异常,但记录实际上未更新/不受影响。但是,如果我复制查询字符串并使用从调试器复制的参数值直接在Access中运行它,它将按预期工作(用给定的ID更新一个特定的行)。