Displaying Records with SQL

If the database administrator is familiar with the SQL language, searching and sorting can be done simply by entering an SQL statement into a textbox which is then used to populate a display control.

Selecting Records with the Repeater

In the following example the statement

SELECT * FROM Books WHERE BookType='Database' ORDER BY BookID ASC

is assigned to the AccessDataSource control associated with the Repeater to display an initial set of records. Then, the statement

SELECT * FROM Books WHERE BookType='Graphics' ORDER BY BookPrice DESC

has been entered into a textbox. When the "Select" button clicked, this statement is used to repopulate the Repeater with the chosen records. Any valid SQL statement entered into the textbox retrieves and displays the associated records. The only restriction is that all fields (*) must be selected in order to retrieve sufficient data to bind to all of the Repeater's display fields.

SQL Statement:

ID Type Title Author Description Price Qty
DB111 Database Oracle Database K. Loney
Get thorough coverage of Oracle Database 10g from the most comprehensive reference available, published by Oracle Press. With in-depth details on all the new features, this powerhouse resource provides an overview of database architecture and Oracle Grid Computing technology, and covers SQL, SQL*Plus, PL/SQL, dynamic PL/SQL, object-oriented features, and Java programming in the Oracle environment. You'll also find valuable database administration and application development techniques, plus an alphabetical reference covering major Oracle commands, keywords, features, and functions, with cross-referencing of topics.
$69.99 10
DB222 Database Databases in Depth C. J. Date
In Database in Depth, author and well-known database authority Chris Date lays out the fundamentals of the relational model. Don't let a lack to formal education in database theory hold you back. Instead, let Chris's clear explanation of relational concepts, set theory, the difference between model and implementation, relational algebra, normalization, and much more set you apart and well above the competition when it comes to getting work done with a relational database.
$29.95 6
DB333 Database Database Processing D. Kroenke
Revised to reflect the needs of today's users, this 10th edition of Database Processing assures that you will learn marketable skills. By presenting SQL SELECT statements near the beginning of the book readers will know early on how to query data and obtain results-seeing firsthand some of the ways that database technology is useful in the marketplace. By utilizing free software downloads, you will be able to actively use a DBMS product by the end of the 2nd chapter. Each topic appears in the context of accomplishing practical tasks. Its spiral approach to database design provides users with enhanced information not available in other database books on the market.
$136.65 12
DB444 Database Access Database Design S. Roman
When using software products with graphical interfaces, we frequently focus so much on the details of how to use the interface that we forget about the general concepts that allow us to understand and use the software effectively. This is particularly true of a powerful database product like Microsoft Access. Novice, and sometimes even experienced, programmers are so concerned with how something is done in Access that they often lose sight of the general principles that underlie their database applications. Access Database Design and Programming takes you behind the details of the Access interface, focusing on the general knowledge necessary for Access power users or developers to create effective database applications.
$34.95 25
DB555 Database SQL Server 2005 P. Debetta
Get a developer-focused introduction to the new programmability features in the next version of Microsoft SQL Server-including integration with the Microsoft .NET Framework-and learn powerful new ways to manipulate your servers. Whether you're a developer currently working with T-SQL or Microsoft Visual Studio.NET, or you're responsible for database administration, you'll see how to draw from your existing skills and knowledge to exploit new SQL Server technology. With introductory-level code samples written in both T-SQL and C#, you'll understand how to take advantage of the cross-platform interoperability, native support for XML and Web services, shared language base, and other programming innovations to build better solutions from business intelligence to enterprise data management.
$29.99 0

Figure 8-19. Selecting records with SQL statements for a Repeater control.

If an error is made in typing the SQL statement, an error message is displayed below the textbox. You can check this out by corrupting the above displayed SQL statement.

Coding the Repeater

Coding for the Repeater is identical to that used in previous examples. <asp:TextBox>, <asp:Button>, and <asp:Label> controls are added to solicit the SQL statement, call the Display_Repeater subprogram, and display an error message if the SQL statement is invalid.

<asp:AccessDataSource id="BookSource" Runat="Server"
  DataFile="../Databases/BooksDB.mdb"
  SelectCommand="SELECT * FROM Books WHERE BookType='Database' 
                 ORDER BY BookID ASC"/>

<b>SQL Statement:</b><br/>
<asp:TextBox id="SQLStatement" TextMode="MultiLine" Columns="60" 
Font-Size="9pt" Runat="Server"
Text="SELECT * FROM Books WHERE BookType='Graphics' " & _
     "ORDER BY BookPrice DESC"/>
<asp:Button Text="Select" Runat="Server" OnClick="Display_Repeater"/><br/>
<asp:Label id="ERRMsg" EnableViewState="False" ForeColor="#FF0000" 
  Runat="Server"/>

<asp:Repeater id="RepeaterDisplay" DataSourceID="BookSource" Runat="Server">
  <HeaderTemplate>
    <table id="RepeaterTable" border="1" style="width:530px; 
    border-collapse:collapse">
    <tr style="background-color:#707070; color:#FFFFFF">
      <th>ID</th>
      <th>Type</th>
      <th>Title</th>
      <th>Author</th>
      <th>Description</th>
      <th>Price</th>
      <th>Qty</th>
    </tr>
  </HeaderTemplate>
  <ItemTemplate>
    <tr style="vertical-align:top">
      <td style="text-align:center">
          <asp:Label Text='<%# Eval("BookID") %>' Runat="Server"/></td>
      <td><asp:Label Text='<%# Eval("BookType") %>' Runat="Server"/></td>
      <td><asp:Label Text='<%# Eval("BookTitle") %>' Runat="Server"/></td>
      <td><asp:Label Text='<%# Eval("BookAuthor") %>' Runat="Server"/></td>
      <td><asp:Panel ScrollBars="Auto" Width="180" Height="60" Runat="Server">
            <asp:Label Font-Size="9" Style="line-height:10pt" Runat="Server"
            Text='<%# Eval("BookDescription") %>'/><br/>
          </asp:Panel></td>
      <td style="text-align:right">
          <asp:Label Text='<%# Eval("BookPrice") %>' 
          Runat="Server"/></td>
      <td style="text-align:right">
          <asp:Label Text='<%# Eval("BookQty") %>' 
          Runat="Server"/></td>
    </tr>
  </ItemTemplate>

  <FooterTemplate>
    </table>
  </FooterTemplate>
</asp:Repeater>
Listing 8-27. Code for Repeater and TextBox to enter SELECT statement.

Notice that the textbox has the property setting TextMode="MultiLine" with 60 columns and a default of 2 rows. The label for the error message is coded with EnableViewState="False" so that error messages are cleared when re-posting the form.

Executing the SQL Command

When the "Submit" button is clicked, the Display_Repeater subprogram is called. As long as a valid SQL statement is entered into the textbox, coding of this subprogram is as simple as assigning the statement to the SelectCommand property of the Access Data Source.

Sub Display_Repeater (Src As Object, Args As EventArgs)
  BookSource.SelectCommand = SQLStatement.Text
End Sub
Listing 8-28. Assigning SELECT statement to SelectCommand property of AccessDataSource for Repeater.

However, if an invalid statement is entered, an execution error occurs. When using an AccessDataSource to populate the Repeater, there is no way to test for this error to handle it elegantly. The subprogram simply aborts and a system error is generated, leaving the user unsure of what happened. Therefore, a different tactic must be used to trap these errors and recover from them.

A run-time error can be trapped only by using a data access script to discover the error. This amounts to issuing the SQL statement through an OleDbCommand object, not through an AccessDataSource. Coding to accomplish this error checking in the Display_Repeater subprogram is shown below. It checks for an invalid SQL statement and displays a "friendly" error message if the statement cannot be properly executed.

<%@ Import Namespace="System.Data.OleDb" %>

<SCRIPT Runat="Server">

Sub Display_Repeater (Src As Object, Args As EventArgs)

  Try
    Dim DBConnection As OleDbConnection = New OleDbConnection( _
      "Provider=Microsoft.Jet.OLEDB.4.0;" & _
      "Data Source=" & Server.MapPath("../Databases/BooksDB.mdb"))
    DBConnection.Open()
    Dim DBCommand = New OleDbCommand(SQLStatement.Text, DBConnection)
    DBCommand.ExecuteReader()
    DBConnection.Close()
    BookSourceSource.SelectCommand = SQLStatement.Text
  Catch
    ERRMsg.Text &= "-- Error in SQL statement --"
    ERRMsg.Visible = True
  End Try
  
End Sub

</SCRIPT>
Listing 8-29. Trapping run-time errors with Try...Catch statement.

Since a script is used to access the BooksDB.mdb database, the System.Data.OleDb namespace must be imported to the page.

Using Try...Catch

The Visual Basic Try...Catch structure is used to encapsulate code that can cause execution errors. Its general format is shown below.

Try
	
  ...execution code
	
Catch
	
  ...error code
	
End Try
Figure 8-20. General format for Try...Catch structure.

Code that can cause run-time execution errors is placed inside the Try section; code to respond to an error is placed inside the Catch section. If there is execution failure in the Try code, the Catch code is run instead. In the above example, database access with the SQL statement is in the Try section; display of an error message appears in the Catch section.

Notice that the OleDbCommand directly executes the entered SQL statement, that is, the Text property of the SQLStatement TextBox. The Command's ExecuteReader() method is the one that can cause a run-time error which is trapped by the Try section of code.

No recordset is returned by the ExecuteReader() method. It is used only to test whether or not the entered SQL statement is valid and can be issued without error. If an error occurs, the remaining statements in the Try section of script are skipped and the Catch section of code is run. If no error is generated, then the SQL statement is valid. The final statement in the Try section assigns the entered SQL command to the SelectCommand property of the AccessDataSource and the subset of records are returned for display.

Similar techniques can be used with any of the information display controls.