10 Database access and DepartmentDAO
-
If needed, retrieve the OOP Company project up to chapter 9 from DLO. It contains the classes as you left them at the end of chapter 9.
-
A file
CreateInsertScriptCompany.sqlis available on DLO. Download it and run it in MySQL Workbench. This creates a database with departments, persons and employees. A user with a password is also created. -
Add the MySQL connector to your project (e.g.
MySql.Datavia NuGet):
a) In Visual Studio: right-click the project → Manage NuGet Packages → search for MySql.Data.
b) Install the package. -
Create a new
Databasefolder in your project. -
A generic
DatabaseAccessclass is available on DLO. Download it and place it in the folder you just created. It will then be visible in your project. -
Create a new
DepartmentDAOclass with the methodSaveDepartment(Department department), which saves a (new) department to the database. -
Test your code by creating a department named HR in Hilversum in the database from your launcher.
a) Do not forget to set up database access first with the correct database, user and password. These can be found in the SQL script.
b) Do not forget to create an instance of theDepartmentDAOclass. -
Create a new method
GetDepartmentsByLocation(string location)that returns a list of departments for the given location. -
Test your code by displaying all departments that are in Hilversum. Your output should look like:
1 2
department HR at Hilversum department Operations at Hilversum -
Finally, add a new employee to the database. This employee is named Lodewijk, lives in Zaandam, works in the Support department in Amsterdam and earns € 2500 per month.
a) Because of subtyping you must update two tables (Person and Employee). You therefore need two DAOs.
b) The primary key for the Person table is auto increment. You need the generated key to update the Employee table.