3

我正在尝试从 C# 中的程序更新数据库。

date这是我连接到数据库的代码以及更新表中列的尝试RoomsTable。对我来说看起来不错,但数据库中没有任何反应。

updateConnection = new System.Data.OleDb.OleDbConnection();
updateConnection.ConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=c:\users\spreston\documents\visual studio 2012\Projects\roomChecksProgram\roomChecksProgram\roomsBase.accdb";
updateConnection.Open();

MessageBox.Show("Connected");

string updateCommand = "UPDATE RoomsTable SET Date Checked='9/27/2012'";
updateAdapter = new OleDbDataAdapter(updateCommand, updateConnection);

updateConnection.Close();
updateConnection.Dispose();

我不知道为什么它不起作用。在我看来,一切都在那里。

4

2 回答 2

9

利用OleDBCommand

string updateCommand = "UPDATE RoomsTable SET [Date Checked]='9/27/2012'";
updateCommand = new OleDbCommand(updateCommand, updateConnection);

updateCommand.ExecuteNonQuery();
updateConnection.Close();

也许你可以使用Using statement参数化查询来重构代码。并且列名Date Checked应该用括号转义。

string updateCommand = "UPDATE RoomsTable SET [Date Checked]=@checkedDate WHERE ID = @id"; // '9/27/2012'
using (OleDbConnection conn = new OleDbConnection("connectionStringHERE"))
{
    using (OleDbCommand comm = new OleDbCommand())
    {
        comm.Connection = conn;
        comm.CommandText = updateCommand;
        comm.CommandType = CommandType.Text
        comm.Parameters.AddWithValue("@checkedDate", this.dateTimePicker1.Value)
        comm.Parameters.AddWithValue("@id", row.roomID);
        try
        {
            comm.Open();
            conn.ExecuteNonQuery();
        }
        catch(OleDbException ex)
        {
            MessageBox.Show(ex.Message.ToString());
        }
    }
}
于 2012-09-30T15:58:29.063 回答
0

你必须这样写:

updateConnection = new System.Data.OleDb.OleDbConnection();
updateConnection.ConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=c:\users\spreston\documents\visual studio 2012\Projects\roomChecksProgram\roomChecksProgram\roomsBase.accdb";

updateConnection.Open();

MessageBox.Show("Connected");

string updateCommand = "UPDATE RoomsTable SET Date Checked= '"+9/27/2012+"' ";

updateAdapter = new OleDbDataAdapter(updateCommand, updateConnection);

updateConnection.Close();
updateConnection.Dispose();
于 2014-10-15T16:46:15.373 回答