Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking if INSERT INTO statement was successful

I am using a MS Access database as the backend of my VB.NET application. I am entering users details into the database using an INSERT INTO statement:

cn = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" & config("DatabasePath") & ";")
cn.Open()
cmd = New OleDbCommand("INSERT INTO blah blah blah...", cn)
dr = cmd.ExecuteReader

Everything works, but I wanted to check if the data has actually been entered into the database. I have tried using:

cn = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" & config("DatabasePath") & ";")
cn.Open()
cmd = New OleDbCommand("INSERT INTO blah blah blah...", cn)
dr = cmd.ExecuteReader
If dr.Read() Then
    ' Blah
End If

but obviously the insert statement doesn't return anything so this doesn't work. Any suggestions?

like image 445
Dox Avatar asked Feb 09 '10 09:02

Dox


People also ask

How do I know if my insert was successful?

You can check the @@ROWCOUNT right after insert. If it's more than 0, then the insert succeeded. Also, if @@ERROR = 0 after insert, it was successful. No, check it in T-SQL although if the insert will result in error, most likely the error will be propagated into the client.

How do I know if SQL Server insert was successful?

You can use @@ROWCOUNT server variable immediately after the insert query to check number of affected rows by the insert operation.

How can we check insert is successful in SQL PHP?

To check if your INSERT was successful, you can use mysqli_affected_rows() . Returns the number of rows affected by the last INSERT, UPDATE, REPLACE or DELETE query. And check for errors against your query and for PHP.


1 Answers

If all you have is the INSERT statement you can use the ExecuteNonQuery() method which returns how many rows were affected.

Like this:

cmd = New OleDbCommand("INSERT INTO blah blah...", cn)
rowCount = cmd.ExecuteNonQuery()
If rowCount < 1 Then 
    ' Blah

You have to excuse me if the VB isn't correct, I didn't test it, but I hope you get the idea.

like image 72
Mats Fredriksson Avatar answered Sep 28 '22 06:09

Mats Fredriksson