UPDATE语句中的语法错误

时间:2016-01-20 11:35:31

标签: c# ms-access

这段代码有什么问题?我做了一切,但我仍然得到了

  

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 个答案:

答案 0 :(得分:2)

我建议您使用参数化查询代替您当前使用的查询。这将解决问题,也可以帮助您防止SQL注入:

以下是一个例子:

string sql = "UPDATE APPOINTMENTS Set [CustomerID]=@id,[DateTime]=@dateTime,[Time]=@time WHERE [CustomerID]=@customerid";
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 :(得分: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 ,然后使用 Format ToString 创建要连接的文本。

或使用参数。

答案 2 :(得分:-1)

更改更新查询 使用这个

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

同时检查DateTime列的数据类型