更新SQL命令C#

Sto*_*123 3 c# sql database sql-update

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

这是我的代码,它连接到数据库并尝试更新表中的dateRoomsTable.它看起来不错,但数据库中没有任何反应.

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();
Run Code Online (Sandbox Code Playgroud)

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

Joh*_*Woo 9

使用 OleDBCommand

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

updateCommand.ExecuteNonQuery();
updateConnection.Close();
Run Code Online (Sandbox Code Playgroud)

也许你可以使用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());
        }
    }
}
Run Code Online (Sandbox Code Playgroud)