试图发现语法错误

时间:2017-05-29 14:56:23

标签: c# sql

尝试在我的代码中更新用户信息时出现此错误...

  

ErrorSystem.Data.OleDb.OleDbException(0x80040E14):语法错误   更新声明。在   System.Data.OleDb.OleDbCommand.ExecuteCommandTextErrorHandling(OleDbHResult   hr)at   System.Data.OleDb.OleDbCommand.ExecuteCommandTextForSingleResult(tagDBPARAMS   dbParams,Object& executeResult)at   System.Data.OleDb.OleDbCommand.ExecuteCommandText(对象&安培;   executeResult)at   System.Data.OleDb.OleDbCommand.ExecuteCommand(的CommandBehavior   行为,对象& executeResult)at   System.Data.OleDb.OleDbCommand.ExecuteReaderInternal(的CommandBehavior   行为,String方法)at   System.Data.OleDb.OleDbCommand.ExecuteNonQuery()at   clsDataLayer.UpdateUser(String userName,String favProgram,String   City,String leastFav,String State,DateTime Date,Int32 userID1)in   c:\ Users \ John Vinson \ Documents \ Visual Studio   2015 \ WebSites \ ProgramAnonymous \ App_Code \ clsDataLayer.cs:第56行   useraccount_details.updateinfo_Click(Object sender,EventArgs e)in   c:\ Users \ John Vinson \ Documents \ Visual Studio   2015 \ WebSites \ ProgramAnonymous \ useraccount_details.aspx.cs:第57行

这是代码......

public void UpdateUser(string userName, string favProgram, string City, string leastFav,
        string State, DateTime Date, int userID1)
    {
        dbConnection.Open();

        string sqlStmt = "UPDATE users SET userName = @username1, " +
            "favProgram = @favprogram1, " +
            "city = @city1, " +
            "state = @state1, " +
            "leastFavProgram = @leastfavprogram, " +
            "dateComplete = @datecomplete, " +
            "WHERE (users.userID = @id)";

        OleDbCommand dbCommand = new OleDbCommand(sqlStmt, dbConnection);

        OleDbParameter param = new OleDbParameter("@username1", userName);
        dbCommand.Parameters.Add(param);

        dbCommand.Parameters.Add(new OleDbParameter("@favprogram1", favProgram));
        dbCommand.Parameters.Add(new OleDbParameter("@city1", City));
        dbCommand.Parameters.Add(new OleDbParameter("@state1", State));
        dbCommand.Parameters.Add(new OleDbParameter("@leastfavprogram", leastFav));
        dbCommand.Parameters.Add(new OleDbParameter("@datecomplete", Date));
        dbCommand.Parameters.Add(new OleDbParameter("@id", userID1));

        dbCommand.ExecuteNonQuery();

        dbConnection.Close();

    }

1 个答案:

答案 0 :(得分:1)

为了避免这样讨厌的语法错误,不要从块中构建(连接)查询,使用 verbatim 字符串将查询设置为可读字符串:

    string sqlStmt = 
      @"UPDATE users
           SET userName = @username1,
               favProgram = @favprogram1,
               city = @city1,
               leastFavProgram = @leastfavprogram,
               dateComplete = @datecomplete -- <- no comma ',' should be here
         WHERE (users.userID = @id)"; 

有一个简单的开发过程:打开SQL编辑器,编写正确的查询然后将其(复制+粘贴)放入@""