Performing a Query with a DataReader
To
retrieve records with a Command
and
DataReader
, you need to use the SELECT statement,
which identifies the table and rows you want to retrieve, the filter
and ordering clauses, and any table joins:
SELECTcolumns
FROMtables
WHEREsearch_condition
ORDER BYorder_expression ASC | DESC
When writing a SELECT statement with a large table, you may want to limit the number of returned results to prevent your application from slowing down dramatically as the database grows. Typically, you accomplish this by adding a WHERE clause that limits the results.
Example 5-1 shows a sample Windows application that fills a list box with the results of a query. The designer code is omitted.
// DataReaderFillForm.cs - Fills a ListBox using System; using System.Windows.Forms; using System.Data.SqlClient; public class DataReaderTest : Form { private ListBox lstNames; private string connectionString = "Data Source=localhost;" + "Initial Catalog=Northwind;Integrated Security=SSPI"; public DataReaderTest() { lstNames = new ListBox(); lstNames.Dock = DockStyle.Fill; Controls.Add(lstNames); Load += new EventHandler(DataReaderTest_Load); } public static void Main() { DataReaderTest t = new DataReaderTest(); Application.Run(t); } private void DataReaderTest_Load(object sender, System.EventArgs e) { string SQL = "SELECT ContactName FROM Customers"; // Create ADO.NET objects. SqlConnection con = new SqlConnection(connectionString); ...
Get ADO.NET in a Nutshell now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.