Datasheet

string queryString = "SELECT [Products].[ProductName], "
"[Products].[QuantityPerUnit], [Products].[UnitPrice]," +
"[Products].[UnitsInStock] FROM [Products] " +
"WHERE ([Products].[CategoryID] = " + CategoryID + ")";
This simply appends the CategoryID value (from the function argument) into the SQL string. Why is
this bad when it achieves the same objectives while using lesser code? The answer has to do with
hacking. This type of method potentially allows what are known as SQL Injection Attacks, which are 'very
bad things' (do a Web search for more details on SQL Injection). If you have a scale for 'bad things to do',
then this is right up there, at the top!
Using Parameters protects you from this. Although it has the same effect, the processing ADO.NET does
secure you against this type of attack.
Although using Parameters involves a little more work, it's much safer and should always be used.
The OleDataAdapter Object
The OleDbDataAdapter contains the commands used to manipulate data. The four Command objects it
contains are held as properties;
SelectCommand, UpdateCommand, InsertCommand, and
DeleteCommand. The SelectCommand is automatically run when the Fill() method is called. The
other three commands are run when the
Update method is called – we'll be looking at this in the next
chapter.
The DataSet Object
While the other objects we've looked at have different classes for different databases, the DataSet is
common to all databases, and is therefore in the
System.Data namespace. It doesn't actually
communicate with the database – the
DataAdapter handles all communication.
The
DataSet has many properties and methods; we'll look at them in the next chapter. Since this chapter
is concentrating on displaying data, all you need to remember is that when we fetch data it is stored in
the
DataSet, and then we bind controls to that data.
The DataReader Object
The DataReader, an object that we haven’t come across yet, is optimised for reading data. When dealing
with databases, connecting to them and fetching the data can often be the longest part of a page,
therefore we want to do it as quickly as possible. We also want to ensure that the database server isn't
tied up – we want not only to get the data quickly, but also stay connected to the database for as little
time as possible.
For this reason we aim to open the connection to the database as late as possible, get the data, and close
the connection as soon as possible. This frees up database resources, allowing the database to process
other requests. This is the technique that the
DataAdapter uses when filling a DataSet. If you manually
open a connection, it isn't automatically closed.
278
Chapter 8
57084_08.qxp 30/01/2004 8:03 PM Page 278