SQL Update语句错误

时间:2012-08-01 09:41:02

标签: c# sql ms-access ado.net

这个SQL UPDATE语句出了什么问题?

try
{
   int ageValue = Int32.Parse(age.Text);

   string updateQuery = "Update \nMyTable \nSet \nFName = '" + fname.Text.ToString() + "',\nLName = '" + lname.Text.ToString() + "',\nAge = " + ageValue + ",\nCome = '" + from.Text.ToString() + "',\nTo = '" + to.Text.ToString() + "' Where Age=" + ageValue + ";";

   MessageBox.Show(updateQuery);

   OleDbConnection con = new OleDbConnection("provider=Microsoft.JET.OLEDB.4.0; Data Source = Database5.mdb");

   OleDbCommand com = new OleDbCommand(updateQuery, con);

   con.Open();
   com.ExecuteNonQuery();
   con.Close();
}
catch (FormatException ex)
{
    MessageBox.Show(ex.Message);
}
catch (OleDbException ex)
{
    MessageBox.Show(ex.Message);
}

我收到了该错误

  

更新语句中的语法错误

SQL Update有什么问题?

工具:

  • Microsoft Access 2003
  • Microsoft Visual Studio 2010 C#

请提前帮助和谢谢

5 个答案:

答案 0 :(得分:2)

尝试摆脱\ n垃圾。

string updateQuery = "Update MyTable Set FName = '" + fname.Text.ToString() + "',LName = '" + lname.Text.ToString() + "',Age = " + ageValue + ",Come = '" + from.Text.ToString() + "',To = '" + to.Text.ToString() + "' Where Age=" + ageValue;

输出连接的结果并尝试运行它。如果这不起作用,请在此处发布连接结果,并且某人应该能够提供帮助。如果不知道连接的结果,就很难知道什么是错的。

答案 1 :(得分:2)

尝试更改此类查询(删除\n和最终;

string updateQuery = "Update MyTable Set FName = '" + fname.Text.ToString() + 
    "', LName = '" + lname.Text.ToString() + "', Age = " + ageValue + 
    ", Come = '" + from.Text.ToString() + "', To = '" + to.Text.ToString() + 
    "' Where Age=" + ageValue;

答案 2 :(得分:0)

我建议您启用Sql Profiler并跟踪您的更新查询,因为它很容易读取连接的查询字符串

答案 3 :(得分:0)

您好,您可以尝试使用此代码

StringBuilder  stringBuilder = new StringBuilder() ;
stringBuilder.Append("Update MyTable Set FName = ") ;
stringBuilder.Append(fname.Text.ToString()) ;
stringBuilder.Append(",\nLName = ") ;
stringBuilder.Append(lname.Text.ToString()) ;
stringBuilder.Append(",\nAge = ") ;
stringBuilder.Append(ageValue) ;

stringBuilder.Append(",\nCome = ") ;
stringBuilder.Append(from.Text.ToString()) ;
stringBuilder.Append(",\nTo = ") ;
stringBuilder.Append(to.Text.ToString()) ;

stringBuilder.Append(" Where Age=") ;
stringBuilder.Append(ageValue) ;
stringBuilder.Append(";") ;


var result = stringBuilder.ToString();

答案 4 :(得分:0)

这就是我用C sharp编写内联SQL的方法:

string strSQL = "";
strSQL += "  Update MyTable Set  ";
strSQL += "  FName =  '" + fname.Text.ToString() + "'  ";
strSQL += "  ,LName = '" + lname.Text.ToString() + "'  ";
strSQL += "  ,Age =   '" + ageValue              + "'  ";
strSQL += "  ,Come =  '" + from.Text.ToString()  + "'  ";
strSQL += "  ,To =    '" + to.Text.ToString()    + "'  ";
strSQL += "  Where Age = '" + ageValue + "'  ";

易于阅读并且工作正常。

您也可以在连接数据库之前在查询下面添加它:

Response.Write(strSQL);
return;

这将向您显示发布到服务器的内容,并使查找错误更容易。