Simple Database Connection with Try, Catch and Finally in Asp.net

The following code snippet shows how to connect the database with try, catch and finally in Asp.net.



Dim mySqlConnection as New SqlConnection (ConnectionString)
Dim mySqlCommand as SqlCommand
Dim strSql as String

strSql = "insert into yourtable (f1, f2) values ('f1', 'f2')"
mySqlCommand = new SqlCommand(strSql, mySqlConnection)

Try

mySqlConnection.Open()
mySqlCommand.ExecuteReader(CommandBehavior.CloseConnection)
Message.text = "New Forward information added"

Catch SQLexc as sqlexception

Message.text = Message.text + sqlexc.tostring()

Catch exc as exception

if Instr(1, exc.tostring, "duplicate key") > 0 then
Message.text = Message.text + "Cannot insert duplicate values."
else
Message.text = Message.text + exc.tostring()
end if

Finally

mySqlConnection.Close()
End Try


Comments

No responses found. Be the first to comment...


  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: