【发布时间】:2012-09-30 17:21:14
【问题描述】:
我正在编写一个更新我创建的数据库的应用程序。该应用程序上有一个数据网格视图,它显示来自数据库的数据。 我的应用发生了一些非常奇怪的事情。
这是更新数据库的代码
string updateCommandString = "UPDATE RoomsTable SET [Date Checked]=@checkedDate WHERE ID = @id";
using (OleDbConnection conn = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=c:\users\spreston\documents\visual studio 2012\Projects\roomChecksProgram\roomChecksProgram\roomsBase.accdb"))
{
using (OleDbCommand updateCommand = new OleDbCommand())
{
updateCommand.Connection = conn;
updateCommand.CommandText = updateCommandString;
updateCommand.CommandType = CommandType.Text;
updateCommand.Parameters.AddWithValue("@checkedDate",
this.dateTimePicker1.Value.ToShortDateString());
updateCommand.Parameters.AddWithValue("@id", row.roomID);
try
{
conn.Open();
updateCommand.ExecuteNonQuery();
conn.Close();
conn.Dispose();
}
catch(OleDbException ex)
{
MessageBox.Show(ex.Message.ToString());
}
}
}
现在,当我运行该代码,关闭应用程序并再次运行应用程序时,更改的内容正确显示在连接到数据库的 datagridview 中,但是当我查看实际数据库时,没有任何变化全部。我不知道为什么会这样。
我的 sql update 更新了连接到 datagrid 视图的数据库。 Sow HOW 是显示正确数据但不显示数据库本身的数据网格视图。
编辑: 我以前没有使用过 sql 的经验。
编辑: 交易代码:
string updateCommandString = "UPDATE RoomsTable SET [Date Checked]=@checkedDate WHERE ID = @id";
using (OleDbConnection conn = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=c:\users\spreston\documents\visual studio 2012\Projects\roomChecksProgram\roomChecksProgram\roomsBase.accdb"))
{
OleDbTransaction transaction = null;
using (OleDbCommand updateCommand = new OleDbCommand())
{
updateCommand.Connection = conn;
updateCommand.Transaction = transaction;
updateCommand.CommandText = updateCommandString;
updateCommand.CommandType = CommandType.Text;
updateCommand.Parameters.AddWithValue("@checkedDate", this.dateTimePicker1.Value.ToShortDateString());
updateCommand.Parameters.AddWithValue("@id", row.roomID);
try
{
conn.Open();
transaction = conn.BeginTransaction();
updateCommand.ExecuteNonQuery();
transaction.Commit();
conn.Close();
conn.Dispose();
}
catch(OleDbException ex)
{
MessageBox.Show(ex.Message.ToString());
}
}
}
【问题讨论】:
-
我不确定
dateTimePicker1.Value.ToShortDateString()是否有必要。将 DateTime 转换为字符串是特定于文化的。 -
为什么要使用 conn.Dispose?当您以原子方式使用“使用”对象时 Dispose
-
您是否有可能在其中遇到异常但它不是 OldDbException?如果将捕获扩展到“异常”,您会发现什么吗?
-
如果数据网格从数据库中获取数据,我想不出数据网格显示新更新的数据而不是数据库的任何方式
-
@Kamil 好的,解决了我试图解决的一个问题,即在我提交新日期后更新数据网格视图。但它仍然没有更新实际的数据库
标签: c# ms-access datagridview ado.net