IMAT1604: Visual Web Development

DatabaseQuery Code - Constructors

In C# the name of the Constructor method is the same as the class name, the constructor does not have a return type. DatabaseQuery has two constructors, the constructor without a parameter assumes that the database connection string is called AddressBookDbConnectionString. The other constructor is the one that will be used more often as it creates a connection to any database given the appropriate connection string name.

DatabaseQuery myQuery = new DatabaseQuery("WinesDbConnectionString");

C# DatabaseQuery Class

DatabaseQuery Code - AddParameter

This method needs to be called once for each SQL Parameter in the stored procedure query. The parameters must be added in the correct order. With an INSERT query there will one SQL Parameter for each field in the record, whereas the simplest SELECT query might have no parameters.

C# DatabaseQuery Class

DatabaseQuery Code - Execute()

The code to execute any stored procedure, including Select, Insert, Delete and Update. The database connection is opened, and an SqlCommand is created based on the Stored procedure. The CommandBuilder is used to automatically generate Inser, Delete and Update queries. The DataAdaptor is used to fill the DataTable with the records retrieved by the stored procedure. The database connection is automatically closed at the end of the Using block.

C# DatabaseQuery Class

DatabaseQuery Code - CreateCommand

The CreateCommand method creates an SqlCommand based on the stored procedure name, and the database connection. All the Sql Parameters in the SqlParameters list are then added to this command.

C# DatabaseQuery Class