| Author: ABitSmart 28 Jun 2009 | Member Level: Diamond | Rating:  Points: 2 |
Public Function Execute(ByVal strQuery As String) As Integer Dim recAffected As Integer Try If cn.State = ConnectionState.Open Then //is the connection to any DB open ? cn.Close() //yes, so close it End If Dim cmd As sqlCommand cmd = New sqlCommand(strQuery, cn) //build the command object to execute query cn.ConnectionString = conString //set the new connection properties cn.Open() //connect to the DB recAffected = cmd.ExecuteNonQuery() //execute the query. return the number of rows affected by the query cn.Close() //close the connection since everything is over now Catch ex As Exception //some exception in executing query If cn.State = ConnectionState.Open Then //is the connection open? cn.Close() //close it End If recAffected = -1 //set the number of records affected as -1 indicating some error occurred. End Try Return recAffected //return the total number of records affected by query End Function
|
| Author: ABitSmart 28 Jun 2009 | Member Level: Diamond | Rating:  Points: 2 |
Some optimization to the above code,
Public Function Execute(ByVal strQuery As String) As Integer Dim recAffected As Integer Try Dim cmd As sqlCommand cmd = New sqlCommand(strQuery, cn) //build the command object to execute query cn.ConnectionString = conString //set the new connection properties. Not sure if this needed. Is the connection string changed everytime ? If no, then you do not need this line. cn.Open() //connect to the DB recAffected = cmd.ExecuteNonQuery() //execute the query. return the number of rows affected by the query Catch ex As Exception //some exception in executing query recAffected = -1 //set the number of records affected as -1 indicating some error occurred.
Finally //clean up If cn.State = ConnectionState.Open Then //is the connection open? cn.Close() //close the connection since everything is over now End If End Try Return recAffected //return the total number of records affected by query End Function
|