2016-01-20 88 views
0

此代码有什么问题?我所做的一切,但我仍然得到UPDATE语句中的语法错误

语法错误在UPDATE语句

请帮助。先谢谢你。

OleDbConnection conn = default(OleDbConnection); 

OleDbCommand cmd = default(OleDbCommand); 

conn = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=DemoDB.accdb"); 

string sql = "UPDATE APPOINTMENTS Set ([CustomerID]=" + txtCid.Text + ", [DateTime]= " + dateTimePicker5.Text + ", [Time]=" + txtNewTime.Text + " WHERE [CustomerID]=" + txtCid.Text + ");"; 

conn.Open(); 

cmd = new OleDbCommand(sql, conn); 

cmd.ExecuteNonQuery();//execute the sql command 

MessageBox.Show("Appointment Changed Successful"); 

//close the connectionstring 
conn.Close(); 
+3

使用参数,你将免于这个问题(和其他人) – Steve

+0

我不擅长使用参数你会帮助这么做,请。 –

+0

此链接显示使用参数的示例http://stackoverflow.com/questions/15126427/oledb-update-command –

回答

-1

变化更新查询 使用本

string sql = "UPDATE APPOINTMENTS Set [CustomerID]=" + txtCid.Text + ", [DateTime]= " + dateTimePicker5.Text + ", [Time]=" + txtNewTime.Text + " WHERE [CustomerID]=" + txtCid.Text + " "; 

还要检查你的时间列

+1

但是,当然,我们不建议在sql查询上进行字符串连接,对吧?我们建议他们使用准备好的陈述。 –

2

的数据类型,我建议你使用参数化查询,而不是您当前正在使用的是什么。这样便解决了问题,还可以帮助您防止SQL注入:

下面是一个例子:

string sql = "UPDATE APPOINTMENTS Set [CustomerID][email protected],[DateTime][email protected],[Time][email protected] WHERE [CustomerID][email protected]"; 
using (OleDbConnection cn = new OleDbConnection("Your connection string here")) 
     { 
      using (OleDbCommand cmd = new OleDbCommand(sql,cn)) 
      { 
       cmd.Parameters.Add("@id", OleDbType .VarChar, 50).Value = "Some value Here"; 
       cmd.Parameters.Add("@dateTime", OleDbType.Date).Value = "Some value Here"; 
       cmd.Parameters.Add("@time", OleDbType.DBTime, 50).Value = "Some value Here"; 
       cmd.Parameters.Add("@customerid", OleDbType .VarChar, 50).Value = "Some value Here"; 
       //execute command here 
      } 
     } 
+1

你的意思是'OleDbType'而不是'SqlDbType'我认为:) –

+0

@SonerGönül:辉煌的点,感谢您的建议。我已经更新了答案 –

+0

我使用OLEDBtype不是sqltype,我有一些数据。我不能转移到sqldbtype。 –

0

作为最低要求,必须使用正确的字符串表达式的日期和时间:

string sql = "UPDATE APPOINTMENTS Set ([CustomerID]=" + txtCid.Text + ", [DateTime]= #" + dateTimePicker5.Text + "#, [Time]=#" + txtNewTime.Text + "# WHERE [CustomerID]=" + txtCid.Text + ");"; 

,它可以简化为:

string sql = "UPDATE APPOINTMENTS Set ([DateTime]= #" + dateTimePicker5.Text + "#, [Time]=#" + txtNewTime.Text + "# WHERE [CustomerID]=" + txtCid.Text + ");"; 

然而,这要求你的日期和时间正文格式正确。如果不是,则必须先将这些解析为DateTime,然后使用格式ToString创建要并置的文本。

或使用参数。