根据描述,更新函数没有报错,但是没有更新成功。可以从以下几个方面排查:
try { //创建数据库连接 SqlConnection conn = new SqlConnection(connectionString); conn.Open(); //打开数据库连接 SqlCommand cmd = new SqlCommand("update student set name='newname' where id=1", conn); int result = cmd.ExecuteNonQuery(); //执行更新语句 if (result > 0) { Response.Write("更新成功!"); } conn.Close(); //关闭数据库连接 } catch(Exception ex) { Response.Write(ex.Message); }
更新语句是否正确。可以在SQL Server Management Studio中执行相同的SQL语句,看是否有更新。如果没有更新,则需要检查语句是否正确。
是否有事务影响。如果在更新语句执行之前有开启事务,但没有提交事务,则更新操作无效。可以检查事务是否正常,代码示例如下:
SqlConnection conn = new SqlConnection(connectionString); conn.Open(); SqlTransaction tran = conn.BeginTransaction(); try { SqlCommand cmd = new SqlCommand("update student set name='newname' where id=1", conn, tran); int result = cmd.ExecuteNonQuery(); //执行更新语句 if (result > 0) { Response.Write("更新成功!"); } tran.Commit(); //提交事务 } catch(Exception ex) { tran.Rollback(); //回滚事务 Response.Write(ex.Message); } finally { conn.Close(); //关闭数据库连接 }
通过以上几个方面的排查,就可以找到更新无效的原因,并进行修复。