Friday, January 11, 2013

ADO.NET 2012 - GET DATA from SQL with Using Statements

VB.NET
Private Function GetData() As String

        Dim intDataID As Integer
        Dim strFinalizedDate As String = "Not Completed"

        Try
            intDataID = Int32.Parse(lblDataID.Text)

            Using conn As New SqlConnection(ConfigurationManager.ConnectionStrings("conn_string").ConnectionString)
                conn.Open()
                Using cmd As New SqlCommand("SELECT update_dt FROM table WHERE data_id = " & intDataID, conn)
                    cmd.CommandType = CommandType.Text
                    Using reader As SqlDataReader = cmd.ExecuteReader()
                        If reader.HasRows Then
                           While reader.Read()
                                strFinalizedDate = reader("update_dt").ToString()
                            End While
                        End If
                    End Using
                End Using
            End Using

            Return strFinalizedDate

        Catch ex As Exception
            Throw

        End Try

    End Function

C#
try {
intDataID = Int32.Parse(lblDataID.Text);

using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings("conn_string").ConnectionString)) {
conn.Open();
using (SqlCommand cmd = new SqlCommand("SELECT update_dt FROM table WHERE data_id = " + intDataID, conn)) {
cmd.CommandType = CommandType.Text;
using (SqlDataReader reader = cmd.ExecuteReader()) {
if (reader.HasRows) {
while (reader.Read()) {
strFinalizedDate = reader("update_dt").ToString();
}
}
}
}
}

return strFinalizedDate;

} catch (Exception ex) {
throw;

}

No comments: