1

I have a VB.net script that needs to put information into a table in the database. The catch is that it is based off of an item Id, so when I am updating I cannot just insert the row would like to update the row if it is already there. For this I need to use the Update command like so:

mysqlCommand = New SQLCommand(UPDATE tableName Colum2=Newvalue ... Where Column1=ItemId)

However I am wondering if there is anyway to tell wether or not a line was updated when I run

mysqlcommand.ExecuteNonQuery()

so that I do not need to check before I run this command and switch between this update command and a INSERT INTO command

2 Answers 2

1

I agree with @Neolisk, but a slight improvement could be to use the following:

Dim recordsAffected As Integer = mysqlcommand.ExecuteNonQuery()
If recordsAffected > 0 Then 'it worked

or this:

Dim recordsAffected As Integer = mysqlcommand.ExecuteNonQuery()
If recordsAffected >= 1 Then 'it worked

@Neolisk's code will work great as long as Column1 is a unique identifier. Otherwise you may be updating more than one row. The "greater than"/"greater than or equal to" operator will catch the scenario where you are updating more than one row.

Sign up to request clarification or add additional context in comments.

2 Comments

+1. Thanks for your comment. I updated my answer, hope it looks better now.
@Neolisk - I assumed that's what you were going for. Just wanted to point it out for DoNotArrestMe in case he wasn't aware. I "upvoted" your answer as well since you were the original "responder".
1

From documentation of SqlCommand.ExecuteNonQuery @ MSDN:

Executes a Transact-SQL statement against the connection and returns the number of rows affected.

So you can write like this:

Dim recordsAffected As Integer = mysqlcommand.ExecuteNonQuery()
If recordsAffected = 1 Then 'it worked

EDIT: Regarding @macoms01 answer, my original intention was to have something like this:

Select Case recordsAffected
  Case 0: 'it did not work
  Case 1: 'it worked
  Case Else: Throw New BadDataException
End Select

You can never be sure that unique constraints are set on the DB - expect bad data.

But then I thought it would probably be too complicated for its purpose.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.