【问题标题】:Getting affected row count获取受影响的行数
【发布时间】:2011-10-03 17:35:18
【问题描述】:

更新 1:

这看起来对吗?

Dim objSqlConnection As SqlConnection
Dim objSqlCommand As SqlCommand

Dim intAffectedRowCount As Integer

Function update_function() As Integer
    Using objSqlConnection = New SqlConnection(System.Configuration.ConfigurationManager.AppSettings("connectionString"))
        objSqlCommand = New SqlCommand("update table1 set col1 = @col1 where id = @id", objSqlConnection)

        objSqlCommand.Parameters.Add("@col1", SqlDbType.VarChar, 255).Value = strData
        objSqlCommand.Parameters.Add("@id", SqlDbType.Int, 4).Value = intID

        objSqlCommand.Connection.Open()
        intAffectedRowCount = objSqlCommand.ExecuteNonQuery()
        objSqlCommand.Connection.Close()
    End Using

    return intAffectedRowCount
End Function

这会关闭所有正确打开的东西吗?


原始问题:

我目前正在使用以下代码更新数据库表中的一行:

objSQLConnection = New SqlConnection(System.Configuration.ConfigurationManager.AppSettings("connString"))

objSQLCommand = New SqlCommand("update table1 set col1 = @col1 where id = @id", objSQLConnection)

objSQLCommand.Parameters.Add("@col1", SqlDbType.VarChar, 255).Value = strCol1Data
objSQLCommand.Parameters.Add("@id", SqlDbType.Int, 4).Value = intID

objSQLCommand.Connection.Open()
objSQLCommand.ExecuteNonQuery()
objSQLCommand.Connection.Close()

如果我在 sql server 中运行该查询,它会返回一条消息“受影响的 1 行”。

可能从asp.net访问相同的消息,但我不知道如何访问它。

即使我得到一个计数,即 1。

有人知道如何计算受影响的行数吗?

【问题讨论】:

    标签: asp.net sql sql-server-2005 tsql .net-3.5


    【解决方案1】:

    来自SqlCommand.ExecuteNonQuery 的文档:

    返回值

    类型:System.Int32 受影响的行数。

    所以你正在执行 ExecuteNonQuery 并且当前忽略返回值,只是不要忽略它 :)

    (您还应该使用Using 声明以确保您不会泄漏连接等)

    【讨论】:

    • @nami:我也会对命令使用 Using 语句,但是是的,这基本上是正确的。不过,您可以直接从 ExecuteNonQuery 调用返回 - Using 语句将负责关闭连接。
    猜你喜欢
    • 2019-02-19
    • 1970-01-01
    • 1970-01-01
    • 2011-06-11
    • 2016-11-01
    • 2022-11-10
    • 2012-10-01
    • 1970-01-01
    • 2011-10-28
    相关资源
    最近更新 更多