简体   繁体   中英

Getting affected row count

UPDATE 1:

Does this look right?

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

Does this close off everything opened properly?


ORIGINAL QUESTION:

I am currently using the following code to update a row in a database table:

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()

If I run that query in sql server, it returns a message saying "1 row affected".

It's probably possible to access the same message from asp.net, but I don't know how to access it.

Even if I get a count, ie 1.

Anyone know how to get a count of the rows affected?

From the docs for SqlCommand.ExecuteNonQuery :

Return Value

Type: System.Int32 The number of rows affected.

So where you're executing ExecuteNonQuery and currently ignoring the return value, just don't ignore it:)

(You should also use a Using statement to make sure that you don't leak connections etc.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM