Datasheet
This simply appends the CategoryID value (from the function argument) into the SQL string. Why is
this bad when it achieves the same things, plus uses less code? The answer has to do with hacking. This
type of method potentially allows what are known as SQL Injection Attacks, which are a ‘very bad thing'
(do a Web search for more details on SQL Injection). If you have a scale of ‘bad things to do', then this is
right there up at the top!.
Using Parameters, on the other hand, protects you from this. Although it has the same effect, the
processing ADO.NET does secure you against this type of attack.
So, even though using Parameters is 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, but we're not going to look at them until 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 any 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.
Many times, when fetching data we simply want to display it as it is, perhaps by binding it to a grid. The
DataSet provides a local store of the data, which is often more than we need, so we can use an
OleDbDataReader to stream the data directly from the database into the grid. Let's give this a go.
283
Reading From Databases
57076_Ch 8 SAN.qxd 01/12/2003 6:43 PM Page 283