Try Catch Finally for reading data from SQL server (VB.net)
<%@ Page Language="VB" %>
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SqlClient" %>
<html>
<title>Try-Catch-Finally Example</title>
<head>
<script runat="server">
Sub Page_Load()
' Dim ConnStr As String = "Data Source=(local)\NetSDK;" & _
' "Initial Catalog=Pubs;Trusted_Connection=True;"
Dim ConnStr As String = "Data Source=whsql-v08.prod.mesa1.secureserver.net;Initial Catalog=DB_49907;User ID=java2suser;Password='password';"
Dim SQL As String = "SELECT ID, FirstName FROM Employee " & _
"WHERE ID IS NOT NULL"
Dim PubsConn As New SqlConnection(ConnStr)
Dim TitlesCmd As New SqlCommand(SQL, PubsConn)
Dim Titles As SqlDataReader
Try
PubsConn.Open()
Titles = TitlesCmd.ExecuteReader()
Output.Text = "<table>"
While Titles.Read()
Output.Text &= "<tr>"
Output.Text &= "<td>" & Titles.GetString(0) & "</td>"
' Output.Text &= "<td>$" & _
' Format(Titles.GetDecimal(1), "##0.00") & "</td>"
Output.Text &= "</tr>"
End While
Output.Text &= "</table>"
Catch sqlEx As SqlException
Response.Write("A SqlException has occurred.")
Catch ex As Exception
Response.Write("An Exception has occurred.")
Finally
If Not Titles Is Nothing Then
If Not Titles.IsClosed Then
Titles.Close()
End If
End If
If PubsConn.State = ConnectionState.Open Then
PubsConn.Close()
End If
End Try
Response.Write("<br/>The current connection state is: " & _
PubsConn.State.ToString() & ".")
End Sub
</script>
</head>
<body>
<h1>SqlDataReader Example</h1>
<asp:label id="Output" runat="server"/>
</body>
</html>
Related examples in the same category