2012-09-30 108 views
3

我试图从我的程序在C#中更新数据库。更新SQL命令C#

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

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

你需要运行'的execute()'方法。 –

回答

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][email protected] 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()); 
     } 
    } 
} 
+0

嗯是啊我正在关注我在网上找到的教程..(我没有数据库经验),它使用我使用的方法。这是一个访问数据库和一切即时使用。 – Stonep123

+0

typo:refractor .. – Default

+0

我试过你的方法和我得到错误(“不能隐式转换类型'System.Data.OleDB.OleDBCommand'到字符串)和('字符串'不包含'ExecuteNonQuery' – Stonep123

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(); 
+0

在查询中始终使用参数以避免sql注入。您的updateCommand字符串不是您认为的那样。 – LarsTech