Step 1

advertisement
Practical 3
[ADO.NET]
EXERCISE 1
The tasks in this practical are step by step instructions of how to use ADO.NET to connect to a
database and perform queries such as inserting and retrieving data.
TASK 1: Creating the database
Step 1: Open the Visual Studio File menu, and then select New (or press Ctrl+Shift+n). Then
click on Project, select C# Windows Forms Application and name it e.g. Week3ADO.
Step 2: Right click on the project and select Add, New Item:
Step 3: Search for “Database” and add a Service-based Database and call it
“ProjectManagement.mdf”:
Step 4: This will add be added to your solution as shown below:
Step 5: Open the server explorer located top left of the Window or (Ctrl + Shift + S). The newly
created database should be listed under Data Connections:
Matthew Dorrian & Sean Quinn
Page 1
Practical 3
[ADO.NET]
Step 6: Click on the arrow beside the ProjectManagement.mdf to open the connection to the
database:
*You can notice the Green connection logo instead of red x indicating a successful connection
Step 7: This is a configuration step that is specific to this lab. Right click on the database and select
Modify Connection. Follow the screenshots below to change the database to point to a local SQL
Server instance running inside Visual Studio.
Choose the Change button next to the Data Source field. Then select Microsoft SQL Server and press
Ok. Inside the Server name field, enter (localdb)\v11.0
Now select the Attach Database file checkbox. Browse to the database located inside the Week3ADO
folder and give it a logical name of ProjectManagement. Now press the OK button.
Matthew Dorrian & Sean Quinn
Page 2
Practical 3
[ADO.NET]
Step 8: We will now add the tables in one step. Right click on the ProjectManagement.mdf and
select New Query:
Step 9: Inside the SQL pane, enter the following script. (This will be provided to you):
CREATE TABLE [dbo].[Project] (
[ProjectCode] INT IDENTITY(1,1) NOT NULL,
[ProjectTitle] NVARCHAR (50) NULL,
[ProjectManager] NVARCHAR (50) NULL,
[ProjectBudget] DECIMAL (18) NULL,
PRIMARY KEY CLUSTERED ([ProjectCode] ASC)
);
Matthew Dorrian & Sean Quinn
Page 3
[ADO.NET]
Practical 3
CREATE TABLE [dbo].[Department] (
[DepartmentNo] INT IDENTITY(1,1) NOT NULL,
[DepartmentName] NVARCHAR (50) NULL,
PRIMARY KEY CLUSTERED ([DepartmentNo] ASC)
);
CREATE TABLE [dbo].[Employee] (
[EmployeeNo] INT IDENTITY(1,1) NOT NULL,
[EmployeeName] NVARCHAR (50) NULL,
[DepartmentNo] INT
NULL,
PRIMARY KEY CLUSTERED ([EmployeeNo] ASC),
CONSTRAINT [FK_Employee_ToDepartment] FOREIGN KEY ([DepartmentNo]) REFERENCES
[dbo].[Department] ([DepartmentNo])
);
CREATE TABLE [dbo].[ProjectEmployee] (
[ProjectCode] INT
[EmployeeNo] INT
NOT NULL,
NOT NULL,
[HourlyRate] DECIMAL (18) NULL,
PRIMARY KEY CLUSTERED ([ProjectCode] ASC),
CONSTRAINT [FK_ProjectEmployee_ToProject] FOREIGN KEY ([ProjectCode]) REFERENCES
[dbo].[Project] ([ProjectCode]),
CONSTRAINT [FK_ProjectEmployee_ToEmployee] FOREIGN KEY ([EmployeeNo]) REFERENCES
[dbo].[Employee] ([EmployeeNo])
);
Click Execute button
to save the new tables to the ProjectManagement database.
This will create the four tables needed: Employee, Department, Project, ProjectEmployee.
To verify that the tables have been created, navigate again to server explorer, right click on the
Tables folder and select refresh and the new tables should be present:
LAB SPECIFIC TASK: Configuring the Data Directory for our Project
Now we will add a lab specific configuration code to the Program.cs file. Whenever our project
gets compiled and executed, Visual Studio creates a copy of the database inside the bin/debug
folder of our project. This means that each time our project gets executed; we get a fresh blank copy
Matthew Dorrian & Sean Quinn
Page 4
Practical 3
[ADO.NET]
of the database. Obviously we do not want this, so we change the Data Directory property of the
connection string to point to our database inside the project folder. You will probably not need this
in your C2K Environment.
Create a method SetupDataDirectoryPath() in Program.cs like below.
Call this method before the Application.Run(new Form1()) line inside the main method
of Program.cs.
TASK 2: Setting up the connection and database query
Step 1: We will now add a connection string to the App.config file to allow us to use this to
connect to the database. Open App.config and add the following connection string:
*Note: Make sure the database name is correct
Matthew Dorrian & Sean Quinn
Page 5
Practical 3
[ADO.NET]
Step 2: Now that we have set up the connection string, we will now need a way to connect to the
database using ADO.NET. We will create a new class called ProjectDal which will be used to
connect to the database and perform all queries and operations belonging to Project table. Right
click on the solution and select Add -> Class:
Call it ProjectDal and select Add:
This will add a new empty class to your solution:
Step 3: This class will be used to connect to the database and house all the operations associated
with the table e.g. insert, delete, retrieve data etc. This class will act as a Data Access Layer which we
will be used to communicate with the database. We will first use the connection string to allow us to
connect.
First we will use the Configuration Manager to assign the database connection string to a string
variable:
*Note: You will need the following using statement: using System.Configuration; To use
this package, you must add the System.Configuration reference to the project.
You can do this by right clicking on the References folder inside the project in Solution Explorer, and
selecting Add Reference.
Matthew Dorrian & Sean Quinn
Page 6
Practical 3
[ADO.NET]
* Inside the Assemblies -> Framework, scroll down and select the checkbox next to
System.Configuration. Click the Ok button to add this reference to the project.
Step 4: Next we will add a method to our new class to allow a new project to be added to the
database. Add the following method declaration:
*Note: The method is static and will return an int.
This method will be used to allow us to add a project to the project table. First we will alter the
method to allow the details of the project to be passed in as parameters:
*Note: Project code is not passed in as Project Code is set to Identity in the table which means it is
automatically generated and auto increments. If the Project code is not set up this way, pass in the
project code in the parameters.
Step 5: Next we will add a method to our new class to allow a new project to be added to the
database. We will need to set up the connection to the database using the connection string created
in the earlier steps. We can now use it to create a SqlConnection object:
Matthew Dorrian & Sean Quinn
Page 7
Practical 3
[ADO.NET]
You may notice we have a using() statement around our code. All the using statement does is
automatically disposes of our SqlConnection object upon exit of the final curly brace.
*Note: You will need the following using statement: using System.Data.SqlClient;
Step 6: Now that we have the SqlConnection object, we will open the connection to allow us to add
a record to the project table:
Step 7: We will now create the SQL string we will use to insert the new project and use
string.Format to create the SQL string using the method parameters:
Next we will create a SqlCommand object which will contain the SQL query and the connection:
If you are using a SqlCommand object to insert or delete data from the database, then to execute
that command you need to use the SqlCommand method ExecuteNonQuery(). This command
returns an integer value that indicates the number of rows that were updated.
Execute the insert command and use an int variable to store how many rows were updated:
Since we have now executed the query, we will need to close the connection to the database. Once
closed we will now return the number of rows updated:
Complete AddProject method:
Matthew Dorrian & Sean Quinn
Page 8
Practical 3
[ADO.NET]
TASK 3: Executing the query through the UI
Step 1: We now have the ProjectDal class set up allow us to add a new project to the project
table. We will add a button to the form1 that when clicked, it will add a new project to the project
table.
Using the toolbox, add a button to the screen and use the properties window to name the button
addProjectBtn and set the text of the button to “Add Project”:
Double click on the button to automatically generate the click event method to the code behind:
We will use this method to add a new project to the database and if successful, display a dialog
displaying a success message and an error message if the record isn’t added successfully.
Step 2: Since the AddProject method in the ProjectDal is a static method, it means we do
not need create an instance of the ProjectDal class to call the method. We can call the method
by using the ProjectDal class itself and pass in the new project details:
We know the AddProject method returns the number of rows updated so we will need to catch
the returned number in an int variable.
Matthew Dorrian & Sean Quinn
Page 9
Practical 3
[ADO.NET]
We will use check if the rows affected is greater than 0 and if it is display a successful message and if
not, display an error message:
Run the application and click the button. If the project gets added successfully, we will need to check
the database to see if the record has been added successfully.
Step 3: Open the server explorer located top left of the Window or (Ctr + Shift + S). The database
should be listed under Data Connections:
Click on the arrow beside the ProjectManagement.mdf to open the connection to the
database:
Right click on the Project table, select ‘Show Table Data’ to see if the new record has been added:
TASK 4: Retrieving data from the database
Step 1: We will add a new method to return all projects titles that have a certain manager. This
method will allow the managers name to be passed in as a parameter and to be used to retrieve the
titles of the projects that he manages.
This method will return a list of project titles that the manager owns.
Matthew Dorrian & Sean Quinn
Page 10
Practical 3
[ADO.NET]
Add the following method declaration:
*Note: We will use a list of strings to represent the project titles.
Step 2: Next we will create the SQL string to select all projects where the Project Manager is equal
to the name passed in as the method parameter. Set up the SqlCommand to use the query and the
database connection:
Step 3: Since the SqlCommand is to query data that is to be returned, we will need to use the
ExecuteReader() method that returns an instance of a SqlDataReader. Execute the query
and use a SqlDataReader variable to catch the returned data as a SqlDataReader:
Step 4: Once we have the data reader we will need to add each project title to our project list. Add a
while loop to achieve this using the SqlDataReader Read() method which will advance the
reader to the next record if there is a next record:
*Note: Use the column name to pick out the project title from each row in the Reader.
Matthew Dorrian & Sean Quinn
Page 11
Practical 3
[ADO.NET]
Complete Method:
Step 5: We now have the ProjectDal class set up allow us to find out the project titles of a
specified Manager. We will add a new button to the form1 that when clicked, it will display the
project titles in a dialog.
Using the toolbox, add a button to the screen and use the properties window to name the button
viewProjectBtn and set the text of the button to “View Matthew’s Projects”:
Double click on the button to automatically generate the click event method to the code behind:
We will use this method to display all the project titles that a specific manager manages.
Step 6: Since the GetProjectTitlesByManager method in the ProjectDal is a static
method, it means we do not need create an instance of the ProjectDal class to call the method.
We can call the method by using the ProjectDal class itself and pass in the new project details:
We know the GetProjectTitlesByManager method returns the project titles in a list so we
will need to catch the returned list in a List<string> variable.
Matthew Dorrian & Sean Quinn
Page 12
Practical 3
[ADO.NET]
We will use an if statement to check if the list contains entries and if not display an error dialog to
the user:
If the list contains project titles, we will display them to the user. We will use a StringBuilder to
allow us to add each project title to the string with a new line after each and use a foreach loop to
loop through the projectTitles list and add each to the StringBuilder . We will then use
the MessageBox.Show() to display the projects to the user:
Output:
Step 6: Since we can add a new project and list projects, it is now time to add the functionality to
delete a certain project based on project title. Add a new method to the ProjectDal and a button
that will perform this operation.
Be creative add any method you think would be beneficial to have in the ProjectDal.
Matthew Dorrian & Sean Quinn
Page 13
Download