| Milos How-To |
| Retrieving Data |
Me.DefaultFields = "Product_PK,ProductName"
In many cases however, we need the ability to query data in a more organized and filtered fashion. For instance, we may want to query all records with a certain product name. We could do this by adding a new method. That method could either have a brand new name, or it could overload GetList() with parameter. In this example, we will create a new method:
VB.NET:
Public Overridable Function GetListByName(ByVal productName As String) As DataSet Dim comQuery As IDbCommand comQuery = Me.NewDbCommand("SELECT Product_PK,ProductName FROM Products WHERE ProductName LIKE @Name" ) Me.AddDbCommandParameter(comQuery,"@Name", productName + "%" ) Return Me.ExecuteQuery(comQuery) End Function
C#:
public DataSet GetListByName(string productName) { IDbCommand comQuery = this.NewDbCommand("SELECT Product_PK,ProductName FROM Products WHERE ProductName LIKE @Name" ); this.AddDbCommandParameter(comQuery,"@Name", productName + "%" ); return this.ExecuteQuery(comQuery); }
As you can see, the ExecuteQuery() method makes it very easy to fire data commands against the server back end. Note also that this is done in a very generic fashion. The generated command object is very generic and can be used with most databases. Much of this functionality is based on the NewDbCommand() method which returns a generic command object. (Note: During runtime, this will generate a command object specific to the used database. In SQL Server scenarios for instance, this would be an SqlCommand object.)
Note the user of the Parameters collection on the command object. This is mandatory for all operations! (Especially SQL Server.) Although some versions of the framework may let you get away with specifying where clause conditions directly (...WHERE ProductName LIKE 'A%'), we try to catch such operations whever possible (without too much of a performance hit... which sometimes is difficult). This is done for security reasons, as the parameters collection protects from SQL injection attacks.
Note also that there is a helper method to easily add parameters to the generic command object. One can also use the command object's Parameters collection, however, that is unnecessarily difficult for generic command objects (it would be much easier for more specific command objects, such as SqlCommand).