ExecuteNonQuery()返回受影响的C#的意外行数

这是我的代码

// SqlCommand query = new SqlCommand("INSERT INTO devis (idProposition, identreprise, tauxHoraire, fraisGenerauxMO, fraisGenerauxPiece, beneficeEtAleas, idStatut, prixUnitaireVenteMO ) VALUES(@idproposition, @identreprise, @tauxHoraire, @fraisGenerauxMO, @fraisGenerauxPiece, @beneficeEtAleas, 1, @prixUnitaireVenteMO) ", Tools.GetConnection()); SqlCommand query = new SqlCommand("INSERT INTO devis (idProposition, identreprise, tauxHoraire, fraisGenerauxMO, fraisGenerauxPiece, beneficeEtAleas, idStatut, prixUnitaireVenteMO, alerteEntrepriseEnvoyee,fraisDeplacement ) VALUES(1051, 85, 20, 2, 2, 2.2, 1, 88,0,-1) ", Tools.GetConnection()); //query.Parameters.AddWithValue("idproposition", this.ID); //query.Parameters.AddWithValue("identreprise", competitor.ID); //query.Parameters.AddWithValue("tauxHoraire", competitor.CoefTauxHoraire); //query.Parameters.AddWithValue("fraisGenerauxMO", competitor.CoefFraisGenerauxMO); //query.Parameters.AddWithValue("fraisGenerauxPiece", competitor.CoefFraisGenerauxPiece); //query.Parameters.AddWithValue("beneficeEtAleas", competitor.CoefBeneficeEtAleas); //query.Parameters.AddWithValue("prixUnitaireVenteMO", Math.Round(competitor.CoefTauxHoraire * competitor.CoefFraisGenerauxMO * competitor.CoefBeneficeEtAleas, 2)); bool insertOK = (query.ExecuteNonQuery() == 1); if (insertOK) { // DO SOMETHING } 

insertOk为false但在数据库中插入的行包含我指定的所有信息

我手动重建查询以查看问题是否来自query.Parameters,它再次插入没有错误进入数据库但insertOk仍然是假的! 我甚至添加了两个不应该为null的其他字段,但两种情况下的活动都是相同的

有任何想法吗?

对于UPDATE,INSERT和DELETE语句,返回值是受命令影响的行数。

当插入或更新的表上存在触发器时,返回值包括插入或更新操作所影响的行数以及受触发器或触发器影响的行数。 对于所有其他类型的语句,返回值为-1。 如果发生回滚,则返回值也为-1。

它声称返回The number of rows affected. ExecuteNonQuery The number of rows affected. 。 这是不正确的,因为客户端无法知道受影响的行数。 文档错误地假定引擎将报告受影响的行数,但这取决于会话SET NOCOUNT状态。 不要编写假设NOCOUNT始终打开的代码。 如果需要知道受影响的行数,请使用OUTPUT子句 。 依赖于@@ROWCOUNTSET NOCOUNT状态会受到许多极端情况的影响,其中值从一个角度或另一个角度来看是不正确的。

ExecuteNonQuery方法返回System.Int32

对连接执行Transact-SQL语句并返回受影响的行数。

 Return Value Type: System.Int32 The number of rows affected. 

由于您的query.ExecuteNonQuery()返回2 ,因此太明显2 == 1返回false

您的查询将是;

 bool insertOK = (2 == 1); 

DEMO

尝试使用SqlDataAdapter ,以便:

 SqlDataAdapter Adabter = new SqlDataAdapter(); Adabter.InsertCommand = new SqlCommand("INSERT INTO devis values(@idProposition, @identreprise), Tools.GetConnection()); Adabter.InsertCommand.Parameters.Add("@idproposition",SqlDbType.Int).Value = yorID; Adabter.InsertCommand.Parameters.Add("@identreprise", SqlDbType.Int).Value = yorID; Tools.OpenConnection(); int result = Adabter.InsertCommand.ExecuteNonQuery(); Tools.CloseConnection(); if( result > 0 ) { MessageBox.Show("Information Added"); }else { MessageBox.Show("Error"); }