Databases: C# and SQLcomputingat.eeecs.qub.ac.uk/.../2016/05/PracticalWeek02.docx · Web...

28
Practical Week 2 Databases: C# and SQL QUEEN’S UNIVERSITY BELFAST

Transcript of Databases: C# and SQLcomputingat.eeecs.qub.ac.uk/.../2016/05/PracticalWeek02.docx · Web...

Databases: C# and SQL

Queen’s University BelfastPractical Week 2

Table of Contents

PRACTICAL 2............................................................................................................................... 2EXERCISE 1: Connecting the Database to a GUI......................................................................2

Task 1: Create the project....................................................................................................2Task 2: Create the objects...................................................................................................3Task 3: Create the Database object.....................................................................................5Task 3: Creating the Database Access Object......................................................................8Task 4: Coding the EmployeeDBAccess Class....................................................................10Task 5: Code the DepartmentDBAccess Class...................................................................12Task 6: Code the ProjectSalaryDBAccess Class..................................................................13

EXERCISE 2: Setting up the GUI............................................................................................15EXERCISE 3: Cross Table Queries..........................................................................................19

1 | Queen’s University Belfast

PRACTICAL 2EXERCISE 1: Connecting the Database to a GUIThe purpose of this exercise is to create a simple interface that will query a database and return the information to the user. You will use the queries that you created in the previous practical, Practical 1.It is recommended that you redo Practical 1 (choosing the option mostly suitable to you i.e. creating the database in Visual Studio or using Microsoft SQL Server Management Studio). Alternatively we have provided the SQL for you to create the tables and then populate them with data.Task 1: Create the projectStep 1: Create a new Visual C# Windows Forms project in the normal way, call it DB_Prac02.Step 2: Right click on the DB_Prac02 project in the Solution Explorer (the entry with the

symbol) and select Add then click on New Folder, see Figure 1.

Figure 1

Step 3: Name this folder objects, your Solution Explorer should now look like similar to Figure 2.

Figure 2

Step 4: Repeat this process and create two further folders named dbAccess and gui. Step 5: Right click on Form1.cs and choose Delete. Agree to permanently delete this file.Step 6: Right click on the gui folder in the Solution Explorer and select Add -> New Item… In the Add New Item window choose Windows Form, name it SearchForm.cs and click the Add button.Step 7: Double click on Program.cs and update the last line of code to read Application.Run(new SearchForm()). Ensure that you include the DB_Prac02.gui at the top of your class to allow access to the SearchForm class.

2 | Queen’s University Belfast

Task 2: Create the objects.As you have four tables in the ProjectManagement database we are going to create four objects (one to manage each table).Step 1: To create a new object right click on the objects folder select Add and click Class..., see Figure 3.

Figure 3

Step 2: In the Add New Item Window name your class, over-writing the generated Class1 name e.g. Project. Click Add.

Figure 4

3 | Queen’s University Belfast

Step 3: Create your objects based on the Class Diagrams in Figures 5 and 6, (if you get stuck here, ask for a copy of the code listing for this class). Also remember to ensure that the class is set as public.

Figure 5

Step 4: Create the final three object classes and complete as per Class Diagrams in Figure 6.

Figure 6

4 | Queen’s University Belfast

Task 3: Create the Database object.At this stage, we will create the Database object class.Step 1: Right click on the objects folder select Add and Class… Name the class Database and complete as per the Class diagram, in Figure 7.Note: you will have to add the statement using System.Data.SqlClient; to the top of your code. This will give you access to the Sql… objects.

Figure 7

Step 2: Before we connect we need to find the details for the connection string. Open the Server Explorer, right click on Data Connections and select Add Connection. Complete the Add Connection window as per Figure 8. (If you already have an active connection due to redoing Practical 1 first, choose Modify Connection instead to access the same window.)

Figure 8

Step 3: Click on the Advanced button and copy the details in the Data Source box, see Figure 9.

5 | Queen’s University Belfast

.\sqlexpress

You should be able to select ProjectManagement from the dropdown menu

Figure 9

Step 4: Open Notepad and paste in the copied text, see Figure 10.

Figure 10

Step 5: Click Ok in the Advanced Properties window and again in the Add Connection window.Step 6: Now switch over to the file, Database.cs and complete the connect method, to do the following:

Declare and initialise a SqlConnectionStringBuilder object: SqlConnectionStringBuilder scStrBuild = new SqlConnectionStringBuilder();.

Set the values of the SqlConnectionStringBuilder variable as described in Step 4 above, see Figure 11 (make sure your information matches what you copied from the Advanced Properties).

o scStrBuild.DataSource = ".\\sqlexpress";o scStrBuild.InitialCatalog = "ProjectManagement";o scStrBuild.IntegratedSecurity = true;

Initialise the class variable of type SqlConnection, conn, using the String representation of the SqlConnectionStringBuilder object: conn = new SqlConnection(scStrBuild.ToString());.

Try to open a SqlConnection by calling that objects open method, conn.Open(). Catch a SqlException and print it to the console. Check to see if the SqlConnection State member is equal to ConnectionState.Open and

o Return true if it does.o Return false if it does not.

public bool connect() {SqlConnectionStringBuilder scStrBuild = new SqlConnectionStringBuilder();scStrBuild.DataSource = ".\\sqlexpress";scStrBuild.InitialCatalog = "ProjectManagement";scStrBuild.IntegratedSecurity = true;conn = new SqlConnection(scStrBuild.ToString());try { conn.Open();} catch (SqlException ex) { Console.WriteLine(ex);}if (conn.State == ConnectionState.Open) { return true;} else { return false;}

}

6 | Queen’s University Belfast

Copy this text

Figure 11: Complete code for connect method

We will now check if we can connect to the database.Step 7: Right click on SearcForm.cs in the gui folder and select View Code.Step 8: Add the following code to the SearchForm.cs:

o Add a private class variable of type Database called db (you will need to add using DBPrac02.objects;)

o In the SearchForm constructor add the code in Figure 12.public SearchForm() { InitializeComponent(); db = new Database(); if (db.connect()) { MessageBox.Show("Database Connection Successful.", "Success"); } else { MessageBox.Show("Database Connection Unsuccessful.", "Error"); }}

Figure 12

Step 9: Save SearchForm.cs and test your code so far , you should see Figure 13. If you do not get a success message then you will need to check your connection details.

Figure 13

7 | Queen’s University Belfast

Task 3: Creating the Database Access ObjectAs we have four tables and four objects representing these table we are going to need a way to interact with the database to populate our objects.Step 1: Right click on the folder called dbAccess, select Add and click Class… Name this class ProjectDBAccess.Step 2: This class is going to contain your interactions with the Database for the Project Class only. Create this class based on the Class Diagram in Figure 14.

Figure 14

Step 3: We will now code all of the methods. Follow the instructions below:

getAllProjects()This method should complete the following actions:

Create a new List object of type Project, named results. Assign the CreateCommand method of the Conn property of the Database object

created in this class (i.e. db.Conn) to the Cmd property of the Database object created in this class (i.e. db.Cmd).

Set the CommandText property of the db.Cmd to the String “SELECT * FROM Project” Set the Rdr property of the Database object to db.Cmd.ExecuteReader(). Create a while loop that checks the db.Rdr Read() method (this method checks if there

are any more results left in the SqlDataReader Object). Add each result to the List using the getProjectFromReader method. Once the while loop has finished close the Database member Rdr using the

SqlDataReader Close() method. Return the list.public List<Project> getAllProjects() { List<Project> results = new List<Project>(); db.Cmd = db.Conn.CreateCommand(); db.Cmd.CommandText = "SELECT * FROM Project"; db.Rdr = db.Cmd.ExecuteReader(); while (db.Rdr.Read()) { results.Add(getProjectFromReader(db.Rdr)); } db.Rdr.Close(); return results;}

Figure 15

8 | Queen’s University Belfast

getProjectFromReader(SqlDataReader reader) Declare and initialise an empty Project object Set the Id property of the Project object using the GetInt32 method of the reader,

passing it the value of the column (remember these are zero-indexed, therefore id is at 0).

Set the Name property of the Project object using the GetString method of the reader, passing it the value of the column (remember these are zero-indexed, therefore name is at 1).

Set the ManagerName property of the Project object using the GetString method of the reader, passing it the value of the column (remember these are zero-indexed, therefore manager name is at 2).

Set the Budget property of the Project object using the GetDecimal method of the reader, passing it the value of the column (remember these are zero-indexed, therefore budget is at 3).

Return the Project Object

getAllProjectsWithBudget(decimal rate, int op)This method should complete the following actions:

Create a String Object and assign it the value “SELECT * FROM Project WHERE ProjectBudget “

Create a switch statement which executes a case based on the value of the parameter, op

o Case 1 append “=” to the Stringo Case 2 append “>=” to the Stringo Case 3 append “<=” to the Stringo Case 4 append “>” to the Stringo Case 5 append “<” to the Stringo Case 6 append “<>”to the Stringo Default append “=” to the String

Then append the parameter, rate, to the String Create a new List object of type Project, named results. Assign the CreateCommand method of the Conn property of the Database object

created in this class (i.e. db.Conn) to the Cmd property of the Database object created in this class (i.e. db.Cmd).

Set the CommandText property of the db.Cmd to the String created at the start of this method.

Set the Rdr property of the Database object to db.Cmd.ExecuteReader(). Create a while loop that checks the db.Rdr Read() method (this method checks if there

are any more results left in the SqlDataReader Object). Add each result to the List using the getProjectFromReader method. Once the while loop has finished close the Database member Rdr using the

SqlDataReader Close() method. Return the list.

9 | Queen’s University Belfast

getAllProjectsWithManager(String manager) Create a new List object of type Project, named results. Assign the CreateCommand method of the Conn property of the Database object

created in this class (i.e. db.Conn) to the Cmd property of the Database object created in this class (i.e. db.Cmd).

Set the CommandText property of the db.Cmd to “SELECT * FROM Project WHERE ProjectManager = ‘” and append the value of the parameter, manager, to this along with “’”.

Set the Rdr property of the Database object to db.Cmd.ExecuteReader(). Create a while loop that checks the db.Rdr Read() method (this method checks if there

are any more results left in the SqlDataReader Object). Add each result to the List using the getProjectFromReader method. Once the while loop has finished close the Database member Rdr using the

SqlDataReader Close() method. Return the list.

Task 4: Coding the EmployeeDBAccess ClassThis class is going to contain your interactions with the Database for the Employee Class and will be similar to the ProjectDBAccess class.Step 1: Right click on the folder called dbAccess, select Add and click Class… Name this class EmployeeDBAccess.Step 2: This class is going to contain your interactions with the Database for the Employee Class only. Create this class based on the Class Diagram in Figure 17.

Figure 16

Step 3: We will now code all of the methods. Follow the instructions below:

getAllEmployees() Create a new List object of type Employee, named results. Assign the CreateCommand method of the Conn property of the Database object

created in this class (i.e. db.Conn) to the Cmd property of the Database object created in this class (i.e. db.Cmd).

Set the CommandText property of the db.Cmd to “SELECT * FROM Employee”. Set the Rdr property of the Database object to db.Cmd.ExecuteReader(). Create a while loop that checks the db.Rdr Read() method (this method checks if there

are any more results left in the SqlDataReader Object). Add each result to the List using the getEmployeeFromReader method. Once the while loop has finished close the Database member Rdr using the

SqlDataReader Close() method. Return the list.

10 | Queen’s University Belfast

getAllEmployeesByDept(int id) Create a new List object of type Employee, named results. Assign the CreateCommand method of the Conn property of the Database object

created in this class (i.e. db.Conn) to the Cmd property of the Database object created in this class (i.e. db.Cmd).

Set the CommandText property of the db.Cmd to “SELECT * FROM EMPLOYEE WHERE DepartmentNo = ”, and then append the value of the id int.

Set the Rdr property of the Database object to db.Cmd.ExecuteReader(). Create a while loop that checks the db.Rdr Read() method (this method checks if there

are any more results left in the SqlDataReader Object). Add each result to the List using the getEmployeeFromReader method. Once the while loop has finished close the Database member Rdr using the

SqlDataReader Close() method. Return the list.

getEmployeeById(int id) Declare and initialise an empty Employee object. Assign the CreateCommand method of the Conn property of the Database object

created in this class (i.e. db.Conn) to the Cmd property of the Database object created in this class (i.e. db.Cmd).

Set the CommandText property of the db.Cmd to the “SELECT * FROM Employee WHERE EmployeeNo = ”, append the value of the id parameter.

Set the Rdr property of the Database object to db.Cmd.ExecuteReader(). Create a while loop that checks the db.Rdr Read() method (this method checks if there

are any more results left in the SqlDataReader Object). Assign the Employee object, created at the start of this method, to the result returned

from the getEmployeeFromReader method. Once the while loop has finished close the Database member Rdr using the

SqlDataReader Close() method. Return the Employee Object.

getEmployeeFromReader(SqlDataReader reader) Declare and initialise an empty Employee object. Set the Id property of the Employee object, using the GetInt32 method of the reader,

passing it the value of the column (remember these are zero-indexed, therefore the Employee ID is at 0).

Set the Name property of the Employee object using the GetString method of the reader, passing it the value of the column (remember these are zero-indexed, therefore employee name is at 1).

Set the DepartmentId property of the Employee object using the GetInt32 method of the reader, passing it the value of the column (remember these are zero-indexed, therefore department id is at 2).

Return the Employee Object.

11 | Queen’s University Belfast

Task 5: Code the DepartmentDBAccess ClassThis class is going to contain your interactions with the Database for the Department Class and again is very similar to the previous two access classes.Step 1: Right click on the folder called dbAccess, select Add and click Class… Name this class DepartmentDBAccess.Step 2: This class is going to contain your interactions with the Database for the Department Class only. Create this class based on the Class Diagram in Figure 17.

Figure 17

Step 3: We will now code all of the methods. Follow the instructions below:

getAllDepartments() Create a new List object of type Department, named results. Assign the CreateCommand method of the Conn property of the Database object

created in this class (i.e. db.Conn) to the Cmd property of the Database object created in this class (i.e. db.Cmd).

Set the CommandText property of the db.Cmd to “SELECT * FROM Department”. Set the Rdr property of the Database object to db.Cmd.ExecuteReader(). Create a while loop that checks the db.Rdr Read() method (this method checks if there

are any more results left in the SqlDataReader Object). Add each result to the List using the getDepartmentFromReader method. Once the while loop has finished close the Database member Rdr using the

SqlDataReader Close() method. Return the list.

getDepartmentByID(int id) Declare and initialise an empty Department object. Assign the CreateCommand method of the Conn property of the Database object

created in this class (i.e. db.Conn) to the Cmd property of the Database object created in this class (i.e. db.Cmd).

Set the CommandText property of the db.Cmd to the “SELECT * FROM Department WHERE DepartmentNo = ”, append the value of the id parameter.

Set the Rdr property of the Database object to db.Cmd.ExecuteReader(). Create a while loop that checks the db.Rdr Read() method (this method checks if there

are any more results left in the SqlDataReader Object). Assign the Department object, created at the start of this method, to the result

returned from the getDepartmentFromReader method. Once the while loop has finished close the Database member Rdr using the

SqlDataReader Close() method. Return the Department Object.

getDepartmentFromReader(SqlDataReader reader) Declare and initialise an empty Department object.

12 | Queen’s University Belfast

Set the Id property of the Department object, using the GetInt32 method of the reader, passing it the value of the column (remember these are zero-indexed, therefore the Employee ID is at 0).

Set the Name property of the Department object using the GetString method of the reader, passing it the value of the column (remember these are zero-indexed, therefore employee name is at 1).

Return the Department Object

Task 6: Code the ProjectSalaryDBAccess ClassThis class is going to contain your interactions with the Database for the ProjectSalary Class and again is very similar to the previous three access classes.Step 1: Right click on the folder called dbAccess, select Add and click Class… Name this class ProjectSalaryDBAccess.Step 2: This class is going to contain your interactions with the Database for the Project Salary Class only. Create this class based on the Class Diagram in Figure 18.

Figure 18

Step 3: We will now code all of the methods. Follow the instructions below:

getAllProjectSalary() Create a new List object of type ProjectSalary, named results. Assign the CreateCommand method of the Conn property of the Database object

created in this class (i.e. db.Conn) to the Cmd property of the Database object created in this class (i.e. db.Cmd).

Set the CommandText property of the db.Cmd to “SELECT * FROM ProjectSalary”. Set the Rdr property of the Database object to db.Cmd.ExecuteReader(). Create a while loop that checks the db.Rdr Read() method (this method checks if there

are any more results left in the SqlDataReader Object). Add each result to the List using the get ProjectSalaryFromReader method. Once the while loop has finished close the Database member Rdr using the

SqlDataReader Close() method. Return the list.

13 | Queen’s University Belfast

getProjectSalaryByProjID(int id) Create a new List object of type ProjectSalary, named results. Assign the CreateCommand method of the Conn property of the Database object

created in this class (i.e. db.Conn) to the Cmd property of the Database object created in this class (i.e. db.Cmd).

Set the CommandText property of the db.Cmd to the “SELECT * FROM ProjectSalary WHERE ProjectCode = ”, append the value of the id parameter.

Set the Rdr property of the Database object to db.Cmd.ExecuteReader(). Create a while loop that checks the db.Rdr Read() method (this method checks if there

are any more results left in the SqlDataReader Object). Add each result to the List using the get ProjectSalaryFromReader method. Once the while loop has finished close the Database member Rdr using the

SqlDataReader Close() method. Return the list.

getProjectSalaryByEmpID(int id) Create a new List object of type ProjectSalary, named results. Assign the CreateCommand method of the Conn property of the Database object

created in this class (i.e. db.Conn) to the Cmd property of the Database object created in this class (i.e. db.Cmd).

Set the CommandText property of the db.Cmd to the “SELECT * FROM ProjectSalary WHERE EmployeeNo = ”, append the value of the id parameter.

Set the Rdr property of the Database object to db.Cmd.ExecuteReader(). Create a while loop that checks the db.Rdr Read() method (this method checks if there

are any more results left in the SqlDataReader Object). Add each result to the List using the get ProjSalaryFromReader method. Once the while loop has finished close the Database member Rdr using the

SqlDataReader Close() method. Return the list.

getProjectSalaryFromReader(SqlDataReader reader) Declare and initialise an empty ProjectSalary object. Set the ProjId property of the ProjectSalary object, using the GetInt32 method of the

reader, passing it the value of the column (remember these are zero-indexed, therefore the Project Id is at 0).

Set the EmpId property of the ProjectSalary object, using the GetInt32 method of the reader, passing it the value of the column (remember these are zero-indexed, therefore the Employee Id is at 1).

Set the HourlyRate property of the ProjectSalary object using the GetDecimal method of the reader, passing it the value of the column (remember these are zero-indexed, therefore hourly rate is at 3).

Return the ProjectSalary Object

14 | Queen’s University Belfast

EXERCISE 2: Setting up the GUIIn this exercise we will set up the GUI, retrieve content from the database and place it in the appropriate parts of the interface.Step 1: Expand the gui folder in the Solution Explorer, right click on SearchForm.cs and select View Designer.Step 2: Make the form an appropriate size (roughly 640 by 420) and add the following elements so that it looks similar to Figure 19. Remember to name each element appropriately – if you name then differently to Figure 19/20 then remember to update your C# accordingly.

Figure 19

Step 3: Right click on SearchForm.cs and choose View Code. Code the methods as per the class diagram, see Figure 20.Note: Methods or members that are light grey are auto-generated by Visual Studio.

Figure 20

Label

15 | Queen’s University Belfast

Labels

DataGridView: resultsDataGrid

Button: searchBtn

ComboBox: queryCBox

Step 4: We will now code all of the methods. Follow the instructions below:

SearchForm()Update the SearchForm constructor to the following (you have most of this already in place):

Initialise the Database member Call the connect() method of the Database member. If it returns true

o Call the initComboBox() method Otherwise

o Display a MessageBox that has a caption of “Database connection not opened”, with a title of “Error”

initComboBox() Declare and initialise a String array with the following values:

"Select all projects that have a budget over 15000","Select all projects that M Phillips manages","List all employees who work in IT department","List the employees who have an hourly rate of under 23","List the employees who have an hourly rate of over 23"

Iterate over the String array and set each value into the ComboBox Items member using queryChosen.Items.Add(cBoxItems[i]);

createTableForProjectResults(List<Project> list) Set the value of the result size label to the Count property of the list passed in to the

method. Initialise the DataTable variable, set at the top of the class, as a new DataTable. Add the value “Project Code” to the Columns member of the DataTable, i.e.

table.Columns.Add("Project Code"); Add the value “Project Name” to the Columns member of the DataTable Add the value “Project Manager” to the Columns member of the DataTable Add the value “Budget” to the Columns member of the DataTable Loop over the list and, add each element to the Rows member of the Datatable

foreach (Project proj in list) { table.Rows.Add(proj.ID, proj.Name, proj.ManagerName, proj.Budget);

}

Set the value of the DataSource property of the DataGridView object to the value of the DataTable variable: dataGridText.DataSource = table;

createTableForEmployeeResults(List<Employee> list) Set the value of the result size label to the Count property of the list passed into this

method. Initialise the DataTable member as a new DataTable Add the value “Employee Number” to the Columns member of the DataTable Add the value “Employee Name” to the Columns member of the DataTable Add the value “Department Id” to the Columns member of the DataTable Loop over the list and, add each element to the Rows member of the Datatable

o i.e. (emp.EmployeeId, emp.Name, emp.DepartmentID) Set the value of the DataSource property of the DataGridView object to the value of the

DataTable variable.

createTableForDepartmentResults(List<Department> list) Set the value of the result size label to the Count property of the list passed into this

method. Initialise the DataTable member as a new DataTable

16 | Queen’s University Belfast

Add the value “Department ID” to the Columns member of the DataTable Add the value “Department Name” to the Columns member of the DataTable Loop over the list and, add each element to the Rows member of the Datatable

o i.e. (dept.Id, dept.Name) Set the value of the DataSource member of the DataGridView object to the value of the

DataTable

createTableForProjectSalaryResults(List<ProjectSalary> list) Set the value of the result size label to the Count property of the list passed into this

method. Initialise the DataTable member as a new DataTable Add the value “Project Code” to the Columns member of the DataTable Add the value “Employee Number” to the Columns member of the DataTable Add the value “Hourly Rate” to the Columns member of the DataTable Loop over the list and, add each element to the Rows member of the Datatable

o i.e. (pSalary.ProjId, pSalary.EmpId, pSalary.HourlyRate) Set the value of the DataSource property of the DataGridView object to the value of the

DataTable variable.

searchBtn_Click(object sender, EventArgs e) Check to see if the SelectedIndex member of the ComboBox is equal to -1. If it is

o Display a MessageBox informing the user that “You have not selected a query” Otherwise

o Create a switch statement which executes a case based on the value of the SelectedIndex member of the ComboBox

Case 0 call createTableForProjectResults passing a new ProjectDBAccess Object that calls the method getAllProjectsWithBudget passing a decimal that is 15000 and an int of value 4

Case 1 call createTableForProjectResults passing a new ProjectDBAccess Object that calls the method getAllProjectsWithManager passing a string with the value “M Phillips”

Case 2 call createTableForEmployeeResults passing a new EmployeeDBAccess Object that calls the method getAllEmployeesByDept passing an int of value 4

For the default case set the value of the result size label to “0”.

(Note: we haven’t covered cases 3 and 4 yet as they are slightly more complex queries involving interaction with multiple tables for which we have not yet added the necessary methods. These will be covered at the end of the document. Alternatively you could remove the corresponding strings from the array in the initiComboBox method so that the options don’t appear in the first place).

17 | Queen’s University Belfast

Step 4: Return to the Design View for SearchForm and click on the Search Button. In the Properties Panel click on the Events icon and scroll to the click event. If the searchBtn_click method is not visible, select it from the drop down menu, see Figure 21.

Figure 21

Step 5: Save the SearchForm.cs class and test your application , see Figure 22.

Figure 22

Step 6: You should test all of the set queries and then continue to amend the application for other queries you would like to offer. You should also update the result set size appropriately for each query.

18 | Queen’s University Belfast

Events Icon

EXERCISE 3: Cross Table QueriesThe Search combo box includes two queries asking you to list Employees based on a comparison of their hourly rate. With our normalised database, the Employee Table does not contain a column for HourlyRate as this is in the Project Salary table. There are a number of ways to query data across multiple tables including SQL JOIN statements. The flexibility of JOIN will be looked at in a later practical. However, within the framework of the methods we have already coded to date we shall now look at another option to allow for these queries.We have a method to display a List of Employee objects, we just need a way to generate that List based on the corresponding HourlyRate field in the ProjectSalary Table.Step 1: Add the following method to EmployeeDBAccess.cs:

public List<Employee> getAllEmployeesByHourlyRate(decimal rate, int op) Create a List of ProjectSalary objects named projects and assign it to the result of

calling the getAllProjectsWhereHourlyRateOP method on a new instance of ProjectSalaryDBAccess. You should pass in rate and op as parameters to this method call.

Hint: List<ProjectSalary> projects = new ProjectSalaryDBAccess(db).getAllProjectsWhereHourlyRateOP(rate, op);

Declare and initialise a new List of Employee objects called results. Use a for loop from 0 to projects.Count to loop through the projects returned, access

the EmployeeNo field and for each one use results.Add to add the result of calling the getAllEmployeeByID method.

Return results.

Note: this method does not currently check for duplicate Employees being returned in the results list which is possible given the data we have. We will leave this a further additional exercise.Step 2: Add the following method to ProjectSalaryDBAccess.cs:

public List<ProjectSalary> getAllProjectsWhereHourlyRateOP(double rate, int op) Create a String Object and initialise it with the value "SELECT * FROM PROJECTSALARY

WHERE HourlyRate " Create a switch statement which executes a case based on the value of op

o Case 1 append “=” to the Stringo Case 2 append “>=” to the Stringo Case 3 append “<=” to the Stringo Case 4 append “>” to the Stringo Case 5 append “<” to the Stringo Case 6 append “<>”to the Stringo Default append “=” to the String

Append the parameter, rate, to the String. Create a new List object of type ProjectSalary, named results. Assign the CreateCommand method of the Conn property of the Database object

created in this class (i.e. db.Conn) to the Cmd property of the Database object created in this class (i.e. db.Cmd).

Set the CommandText property of the db.Cmd to the String created at the start of this method.

Set the Rdr property of the Database object to db.Cmd.ExecuteReader().

19 | Queen’s University Belfast

Create a while loop that checks the db.Rdr Read() method (this method checks if there are any more results left in the SqlDataReader Object).

Add each result to the List using the getProjectSalaryFromReader method. Once the while loop has finished close the Database member Rdr using the

SqlDataReader Close() method. Return the list.

Step3: Right click on SearchForm in the gui folder of the Solution Explorer and select View Code. Amend the searchBtn_Click method to include cases for the 4th and 5th queries.

Case 3 call createTableForEmployeeResults passing a new EmployeeDBAccess Object that calls the method getAllEmployeesByHourlyRate passing a double/decimal value of 23.00 an int of value 5.

Case 4 call createTableForEmployeeResults passing a new EmployeeDBAccess Object that calls the method getAllEmployeesByHourlyRate passing a double/decimal value of 23.00 an int of value 4.

Step 4: You should now save your work and test the last two queries.

20 | Queen’s University Belfast