temple universitycis-linux2.temple.edu/~sallyk/tutorials_sql_server/sqlsv…  · web viewcreating...

48
CIS 2109 Third/Last SQL Server Lab Creating Stored Procedures & Triggers (Sql Mgt Studio 2005) Accessing a Data Base from a C# Windows Application (Visual Studio 2008) TABLE OF CONTENTS 1. Overview.................................................................. 2 2. SQL Mgt Studio: Review SQL INSERT Statement...............................2 3. Stored Procedures......................................................... 3 A. Create Stored Procedure (Compile and Save to Database)..................3 B. Execute Stored Procedure in SQL Server..................................4 C. More Practice (Another Stored Procedure)................................5 D. Modifying and Deleting Stored Procedures................................6 4. Database Triggers......................................................... 6 A. Create a Trigger (Save it in the Database)..............................6 B. Cause Trigger to be Executed (See Results)..............................8 C. More Practice with Triggers............................................. 9 5. Write a Simple Business Application that Accesses a Database.............10 A. Create New Project in Visual Studio 2008 (Windows Form using C# language) 11 B. Design Windows Form and Name Controls..................................12 C. Add Code to Read from the Database.....................................17 D. Run Your Program....................................................... 19 E. Add Code to INSERT data (USing “Plain SQL” Method).....................20 F. Add Code to INSERT data (USing “Stored Procedure” Method)..............22 1

Upload: others

Post on 16-Aug-2020

13 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Temple Universitycis-linux2.temple.edu/~sallyk/tutorials_SQL_Server/SQLSV…  · Web viewCreating Stored Procedures & Triggers (Sql Mgt Studio 2005) Accessing a Data Base from a

CIS 2109 Third/Last SQL Server LabCreating Stored Procedures & Triggers (Sql Mgt Studio 2005)

Accessing a Data Base from a C# Windows Application (Visual Studio 2008)

TABLE OF CONTENTS

1. Overview............................................................................................................................. 2

2. SQL Mgt Studio: Review SQL INSERT Statement.................................................................2

3. Stored Procedures...............................................................................................................3

A. Create Stored Procedure (Compile and Save to Database)..............................................3

B. Execute Stored Procedure in SQL Server..........................................................................4

C. More Practice (Another Stored Procedure).......................................................................5

D. Modifying and Deleting Stored Procedures.......................................................................6

4. Database Triggers...............................................................................................................6

A. Create a Trigger (Save it in the Database).......................................................................6

B. Cause Trigger to be Executed (See Results)....................................................................8

C. More Practice with Triggers..............................................................................................9

5. Write a Simple Business Application that Accesses a Database........................................10

A. Create New Project in Visual Studio 2008 (Windows Form using C# language).............11

B. Design Windows Form and Name Controls.....................................................................12

C. Add Code to Read from the Database............................................................................17

D. Run Your Program..........................................................................................................19

E. Add Code to INSERT data (USing “Plain SQL” Method)...................................................20

F. Add Code to INSERT data (USing “Stored Procedure” Method)......................................22

G. Add Code to INSERT data (USing “Parameterized SQL” Method)...................................24

H. Comparision of the Three Methods to Modify a Database..............................................26

6. Homework......................................................................................................................... 29

1

Page 2: Temple Universitycis-linux2.temple.edu/~sallyk/tutorials_SQL_Server/SQLSV…  · Web viewCreating Stored Procedures & Triggers (Sql Mgt Studio 2005) Accessing a Data Base from a

1. OVERVIEW

In this lab you will:1. Create a Stored Procedure (save it to the database), execute this Stored Procedure2. Create a Trigger (save it to the database), cause the Trigger to be executed3. Use Visual Studio to create a VERY SIMPLE form (mostly copy/pasting code) to demonstrate the following.

a. How a business app uses SQL to read data from a databaseb. How a business app can uses SQL in 3 different ways to modify data in a database:

Building a “Plain” SQL statement Running a Stored Procedure Using a Parameterized SQL statement

4. Compare the pros and cons of the 3 different methods (listed above) to modify data in a database.5. For homework, you will repeat this lab but using the Products table instead of the my_employee table. That is

to say you will:a. create and run a Stored Procedure that inserts a record into the Products tableb. create a timestamp Trigger on the Products table, cause that trigger to be executedc. create a simple C# Windows App that displays Product records and INSERTs them 3 different ways.

2. SQL MGT STUDIO: REVIEW SQL INSERT STATEMENT

Get into SQL Management Studio and connect to your database. For this lab, you will need a table named my_employee. To create this table, run this script in a Query window:

CREATE TABLE my_employee (employee_id INT PRIMARY KEY NOT NULL, employee_name CHAR(20) NOT NULL, salary MONEY DEFAULT 25000 );

Check that you did create the table by right-clicking on the “tables” folder (under your database) and selecting refresh.

Just to review SQL INSERT syntax (and as a check that your table is created properly), execute this statement to insert a record into the table you just created:

INSERT INTO my_employee (employee_id, employee_name) VALUES (100, 'JOHN JONES' );

Check that you did insert the record by right-clicking on the new my_employee table (under the “tables” folder of your database) and selecting “open table”. Note that it is OK to omit INSERTing into some fields as long as you do not violate any “NOT NULL” constraint.

2

Page 3: Temple Universitycis-linux2.temple.edu/~sallyk/tutorials_SQL_Server/SQLSV…  · Web viewCreating Stored Procedures & Triggers (Sql Mgt Studio 2005) Accessing a Data Base from a

3. STORED PROCEDURES

A Stored Procedure is SQL code that is stored in the database and that can be run whenever needed. It can have input parameters and return results (like a method you may have written in java or any other programming language).

A. CREATE STORED PROCEDURE (COMPILE AND SAVE TO DATABASE)

In SQL Server Management Studio’s Object Explorer, under your database, under Programmability, Right click on Stored Procedure and select “New Stored Procedure”. Some default code comes up (as shown below).

3

Page 4: Temple Universitycis-linux2.temple.edu/~sallyk/tutorials_SQL_Server/SQLSV…  · Web viewCreating Stored Procedures & Triggers (Sql Mgt Studio 2005) Accessing a Data Base from a

After selecting “New Stored Procedure”, you see sample SQL code in the Query window. This sample code shows you what SQL you would need to run in order to (compile and) save a Stored Procedure into the database – it does not run the Stored Procedure, just saves it in the database. Replace the sample code with the code below and then click on execute (icon showing red exclamation point and “execute”).

CREATE PROCEDURE insert_employee ( @myemp_id int, @myemp_name CHAR(20))

AS

BEGIN

INSERT INTO my_employee (employee_id, employee_name)VALUES (@myemp_id, @myemp_name)

END

Check that your new Stored Procedure was saved in the database by opening up “Stored Procedures” under “Programmability” under your database. You might have to right-click refresh the Stored Procedures folder.

Let’s study the body of the Stored Procedure that we just saved – what’s between the BEGIN and END. As you can see, is not much. It just executes an INSERT statement using the two input parameters (an employee id and employee name) as the values for the INSERT.

B. EXECUTE STORED PROCEDURE IN SQL SERVER

To run your newly created procedure, run the following code from any SQL command window.

EXEC insert_employee @myemp_id = 200, @myemp_name = 'sally kyvernitis'

If it says “1 row affected”, you have just inserted a record into the my_employee table. Check to make sure by right-clicking on table my_employee and selecting “open table” (if the table was already open, you must close out that window and reopen it). Run the above statement several times trying to get various error messages. Try the following:

Try to insert a second record with the same employee_id (you should get error message about PK violation and the insert fails).

Try to add a record with a name that is longer than 20 characters. (I notice that there is no error but the text is truncated to 20 characters).

Try to add a record with an employee id that is non-numeric, e.g., @myemp_id = '2n40'. Add another record in (this time with unique ID). Check that the INSERT was successful by closing and re-

opening the table.

These are the kinds of errors that a real application (e.g., Visual Studio project) must prevent from happening. However, the simple form you will create (in Visual Studio) does not prevent this – it allows the errors and displays the error messages on the form for you to see.

4

Page 5: Temple Universitycis-linux2.temple.edu/~sallyk/tutorials_SQL_Server/SQLSV…  · Web viewCreating Stored Procedures & Triggers (Sql Mgt Studio 2005) Accessing a Data Base from a

C. MORE PRACTICE (ANOTHER STORED PROCEDURE)

Here’s an example of a Stored Procedure that does more than just insert a single record. This Stored Procedure gives everyone a pay raise, based on the percentage increase was passed in as a parameter to the Procedure. To have the following Stored Procedure saved into the database, execute the following code in a Query window. (Note that Stored Procedures usually are not observed by anyone, so the part that displays the old salary and new salary are for demonstration purposes and would not be in “production code” – the body would only contain the UPDATE statement.

CREATE PROCEDURE salary_increase (@percent_increase DECIMAL(3,1) = 3.0) /* Name of procedure: salary_increase */ /* Name of input parameter: @percent_increase (all variable names must start with @) */ /* Type of input parameter: DECIMAL (3,1) – 3 digts with one to the right of the decimal point */ /* Default value for input parameter, sets the value for salary increase (if no input provided) to 3% */ AS /* Here comes the actual code of the Procedure - 3 statements: (SELECT, UPDATE, SELECT) */ /* Display old salary*/ SELECT Employee_ID, Employee_name, '$' + CONVERT(CHAR(11), Salary, 1) 'Old Salary' FROM my_employee

/* Increase salary*/ UPDATE my_employee SET salary = salary * ( 1 + @percent_increase / 100)

/* Display new salary*/ SELECT Employee_ID, Employee_name, '$' + CONVERT(CHAR(11), Salary, 1) 'New Salary' FROM my_employee

To execute the Stored Procedure (and have it modify the employee salaries), execute the following code in a Query window. Because you are passing in a 5 as the percentage increase, all employees should have their salaries raised by 5%.

EXEC salary_increase @percent_increase = 5.0

Because all of our records have the default value of $25,000 for salary, this demonstration is not super impressive, but it does provide an example of a computationally intensive Stored Procedure.

You can imagine that running a Stored Procedure (like this one) is much more efficient than having the client read and update one employee record at a time. If the client calls a Stored Procedure (like this one), it just sends a simple command over the network to the DBMS, lets the DBSM do lots of work (on the DB Server, network quiet), and waits for a confirmation message back from the DBMS (all done).

5

Page 6: Temple Universitycis-linux2.temple.edu/~sallyk/tutorials_SQL_Server/SQLSV…  · Web viewCreating Stored Procedures & Triggers (Sql Mgt Studio 2005) Accessing a Data Base from a

D. MODIFYING AND DELETING STORED PROCEDURES

If you want to modify or delete a Stored Procedure, go to the object explorer, right click on the Stored Procedure (from the Object Explorer) and select Modify or Delete. Note that this does not actually delete or modify the Stored Procedure— it just gives you the basic SQL code (in the query window) that you would need to run to do this. You can modify the Stored Procedure code that is displayed in the Query window, but this change does not actually take place in the database until you execute that code (saves the altered Stored Procedure into the database).

4. DATABASE TRIGGERS

Triggers are like Stored Procedures in that they both are code that is stored (and executed) right in the database. The difference between a Trigger and Stored Procedure is in how they get invoked. To invoke a Stored Procedure, you must explicitly call that Stored Procedure, whereas, a Trigger is automatically run whenever a certain database happens. When a Trigger is created (and stored in the database), you specify the event with which the Trigger is to be associated. For example “whenever a Customer record is inserted”, “whenever an Invoice record is deleted”.

A. CREATE A TRIGGER (SAVE IT IN THE DATABASE)

Suppose you wanted the database to track ALL modifications to employee salary – what the old salary was, who updated it when, and what the new salary is. The best way to do this is to create an “on update” trigger for the my_employee table. In order to do this, you first need to create a table that will hold the salary audit information (the old and new salary, who updated it and when) by running the following code in a Query window:

CREATE TABLE audit_my_employee ( employee_ID INT, Old_salary MONEY, New_salary MONEY, dateTime_changed DATETIME, sys_user_name CHAR(20),

CONSTRAINT pk_audit_my_employee PRIMARY KEY (employee_ID, dateTime_changed) );

The beauty of triggers is that the database will ALWAYS run this code (inserting records into audit_my_employee), whenever a my_employee record is updated, no matter from where the change came from –the HR application, an interface that updated it, or a user who attached to the my_employee table through an Access database.

6

Page 7: Temple Universitycis-linux2.temple.edu/~sallyk/tutorials_SQL_Server/SQLSV…  · Web viewCreating Stored Procedures & Triggers (Sql Mgt Studio 2005) Accessing a Data Base from a

Next create the trigger (code). From the Object Explorer, under Tables, under my_employee, right click on Triggers, and select “New Trigger” (as shown below).

When you select “new trigger” on table employee_t, you get some SQL code in the Query window – this is sample code showing you what SQL you need to create a trigger.

7

Page 8: Temple Universitycis-linux2.temple.edu/~sallyk/tutorials_SQL_Server/SQLSV…  · Web viewCreating Stored Procedures & Triggers (Sql Mgt Studio 2005) Accessing a Data Base from a

Replace that sample code (in the query window) with the code below.

CREATE TRIGGER update_salary ON my_employee AFTER UPDATE AS IF UPDATE ( salary ) BEGIN DECLARE @employee_ID INT DECLARE @old_salary MONEY DECLARE @new_salary MONEY

SELECT @old_salary = (SELECT salary FROM deleted) SELECT @new_salary = (SELECT salary FROM inserted) SELECT @employee_ID = (SELECT employee_ID FROM inserted)

INSERT INTO audit_my_employee (employee_ID, Old_salary, New_salary, dateTime_changed, sys_user_name) VALUES (@employee_ID, @old_salary,@new_salary, GETDATE(), USER_NAME() END

Explanation:update_salary name of triggermy_employee table with which the trigger is associatedAFTER UPDATE tells when the trigger should be run (after any my_employee record is updated)IF UPDATE (salary) only when the salary column of a my_employee record is updated, will the code (between

BEGIN and END) be runDECLARE specifies name & type of a local variable to be used within the trigger, 3 of these:

@employee_ID, @old_salary, @new_salary.deleted a virtual table with structure identical to the trigger’s table. The deleted table contains the

record’s values BEFORE the update.inserted a virtual table with structure identical to the trigger’s table. The inserted table contains the

record’s values AFTER the update.INSERT … a normal INSERT statement like you have used in previous labs

Once you execute the code (shown above), then you have associated that “Trigger” code with the event “whenever a my_employee record is Updated”.

B. CAUSE TRIGGER TO BE EXECUTED (SEE RESULTS)

To cause a trigger to be executed, all you need to do is perform the database action (i.e., insert, update or delete) on the table for which the trigger is specified. So,

Open the my_employee table (from Object Explorer, right click the table and select “Open Table”) and modify a couple of salaries (take note of the employee_id, the old salary and the salary as you do this).

Open up audit_my_employee table and you should see a couple of records in there, documenting the fact that you modified the salaries of a couple of my_employee records.

8

Page 9: Temple Universitycis-linux2.temple.edu/~sallyk/tutorials_SQL_Server/SQLSV…  · Web viewCreating Stored Procedures & Triggers (Sql Mgt Studio 2005) Accessing a Data Base from a

C. MORE PRACTICE WITH TRIGGERS

Sometimes you might want to create a trigger that implements a constraint (perhaps more complicated than can be specified with DDL, e.g., schema creation commands). If so, you can create a trigger such as the one below – this trigger makes sure that pay increases don’t exceed an allowed value (in this case, 10%). This trigger uses a transaction ROLLBACK to cancel the UPDATE.

CREATE TRIGGER validate_salary_raise ON my_employee AFTER UPDATE AS IF UPDATE (salary) BEGIN DECLARE @old_salary MONEY DECLARE @new_salary MONEY DECLARE @emp_ID INTEGER

SELECT @old_salary = (SELECT salary FROM deleted) SELECT @new_salary = (SELECT salary FROM inserted) SELECT @emp_ID = (SELECT employee_ID FROM inserted)

/* check if increase is greater than 10% */ IF @new_salary > @old_salary * 1.1 BEGIN SELECT 'Salary Raise Exceeds Policy Limits' ROLLBACK TRANSACTION END ELSE BEGIN SELECT 'Salary Raise Approved' END END;

Test this trigger by updating a couple more salaries in the my_employee table—some with a salary increase under 10% and some over 10%. Those over 10% should not be allowed. Those 10% or under should be allowed.

Note: when you try to enter a salary that is too high, SQL Mgt studio will not let you get off the record (because that is when the record is stored, when you move your cursor off the record). You can press the ESC key to return the record to its original values and then it should let you move off the row.

9

Page 10: Temple Universitycis-linux2.temple.edu/~sallyk/tutorials_SQL_Server/SQLSV…  · Web viewCreating Stored Procedures & Triggers (Sql Mgt Studio 2005) Accessing a Data Base from a

5. WRITE A SIMPLE BUSINESS APPLICATION THAT ACCESSES A DATABASE

In this section, you will create a simple Windows Form using Visual Studio 2008 (C#). You copy/paste code that does the following:

uses SQL to read data from a database uses SQL in 3 different ways to modify data in a database (insert a record to the my_employee table):

o Building a “Plain” SQL statement o Running a Stored Procedureo Using a Parameterized SQL statement

Then, you will study that code to see, how application code actually interacts with a database. At the end of this section, you’ll compare the pros and cons of each approach.

10

Page 11: Temple Universitycis-linux2.temple.edu/~sallyk/tutorials_SQL_Server/SQLSV…  · Web viewCreating Stored Procedures & Triggers (Sql Mgt Studio 2005) Accessing a Data Base from a

A. CREATE NEW PROJECT IN VISUAL STUDIO 2008 (WINDOWS FORM USING C# LANGUAGE) To create your Visual Studio Windows Application:

Click on: Start – All Programs – Visual Studio 2008 Click on: File – New - Project Select:

C# (on the left) as Project Type Windows Forms Application (on the right) as Visual Studio Template Browse to your flash drive, if you have one. If not, you can leave the “location” as it is, but take note that

your project name will be become a folder under My documents\ Visual Studio 2008\Projects. If you ever want to move this project to a different computer, it is this “LabProject” folder that you need to move (or zip and mail yourself, etc).

Give your project a name like “LabProject”. Note that VS copies your Project name into the solution name (this is fine).

11

Page 12: Temple Universitycis-linux2.temple.edu/~sallyk/tutorials_SQL_Server/SQLSV…  · Web viewCreating Stored Procedures & Triggers (Sql Mgt Studio 2005) Accessing a Data Base from a

B. DESIGN WINDOWS FORM AND NAME CONTROLS

Your new project comes with an empty form named Form1. This name is fine for our purposes.

We will be using the Toolbox (icon highlighted red above) to help design our form. Click on the Toolbox icon and then click on its push pin icon (upper right of toolbox pane) to get it to stop auto-hiding.

12

Page 13: Temple Universitycis-linux2.temple.edu/~sallyk/tutorials_SQL_Server/SQLSV…  · Web viewCreating Stored Procedures & Triggers (Sql Mgt Studio 2005) Accessing a Data Base from a

Then locate these controls from the Toolbox. These are the controls that we’ll use in this lab: Button Label RichTextBox TextBox

It doesn’t matter Then locate these controls from the Toolbox. These are the controls that we’ll use in this lab:

13

Page 14: Temple Universitycis-linux2.temple.edu/~sallyk/tutorials_SQL_Server/SQLSV…  · Web viewCreating Stored Procedures & Triggers (Sql Mgt Studio 2005) Accessing a Data Base from a

Drag, drop, move, and size controls from the Toolbox onto your form until your form looks like the one below. The large boxes are RichTextBoxes, the small boxes are TextBoxes, the words on the form are Labels, and the buttons (of course) are Buttons.

TRY NOT TO DOUBLE CLICK on any control as you design your form (not yet). If you do, you’ll find yourself in a code pane – never mind, click back on the “Form1.cs [Design]” tab and keep working.

Note that it does not matter if your button shows text “button1” or “button2” --- as long as it shows some kind of button”. The same is true for the lables. We will be changing the Text in the next step anyway.

14

Page 15: Temple Universitycis-linux2.temple.edu/~sallyk/tutorials_SQL_Server/SQLSV…  · Web viewCreating Stored Procedures & Triggers (Sql Mgt Studio 2005) Accessing a Data Base from a

Next, set the Text Property of all Labels and Buttons so that they show the text as shown in the form below. If the Properties pane is not open on the right, you may have to hover over the “Properties” button (far right of

screen) and click on the push pin to make the Properties pane stay open. (You can also press the F4 key.) To set the text property of a control,

o SINGLE Click (for example), on the label in the upper right of your form. o Then scroll down (in the Properties pane) to the TEXT property. Probably it currently says something

like label3 or label4. Replace this with the words you want to display, e.g., “Database Message” (Do not change the (Name) property – leave this alone.)

o Then, do the same for all other labels and buttons (single click on them, type in the text you want displayed in the Text property).

AGAIN, TRY NOT TO DOUBLE CLICK on any control as you design your form (not yet). If you do, you’ll find yourself in a code pane – never mind, click back on the “Form1.cs [Design]” tab and keep working.

15

Page 16: Temple Universitycis-linux2.temple.edu/~sallyk/tutorials_SQL_Server/SQLSV…  · Web viewCreating Stored Procedures & Triggers (Sql Mgt Studio 2005) Accessing a Data Base from a

Now name the textboxes. In your code (e.g., under the buttons), you reference form controls (e.g., textboxes) by their “(Name)”. You must name these textboxes exactly as shown because the code that you will be copy/pasting in references these names. If the names are not exactly right (including upper/lower case), the program will get compiler errors and won’t run.

To set the (Name) property of a form control, SINGLE Click (for example), on the richTextBox in the upper left of your form Then scroll down (in the Properties pane) to the (Name) property. Probably it currently says something like

richTextBox1 or richTextBox2. Replace this with the (Name) you want to use when you reference this control from your code, e.g., “rtShowDataBox”.

Then, do the same for the other (three) textboxes – name them exactly as shown in the digram below (including upper/lower case).

Then it’s not a bad idea to also name your buttons. The exact name of the button is not so important (because they will NOT be referenced by your code), but if you do name them, it will be easier for you to find your way around in the code. So, here are some suggested names for your buttons:

o btnShowData, btnClearMsg, btnInsertPlain, btnInsertParam, btnInsertSP

Congradulations – you have just designed your first form in a Windows Application !

16

(Name): rtDbMsgBox

(Name):

txtEmp_ID

(Name):

txtEmpName

(Name): rtShowDataBox

Page 17: Temple Universitycis-linux2.temple.edu/~sallyk/tutorials_SQL_Server/SQLSV…  · Web viewCreating Stored Procedures & Triggers (Sql Mgt Studio 2005) Accessing a Data Base from a

C. ADD CODE TO READ FROM THE DATABASE

First, add some insignificant code, just so you know where and how to copy/paste code into a button click event.

1. Double click on the button that shows “Clear Msg” (from the design pane). This will get you inside a method called button1_click (or btnClearMsg_click, or something similar – doesn’t matter).

private void button1_Click(object sender, EventArgs e) {

}

2. Copy the two lines of code just below (from this document) into the button1_click method.

// THIS IS THE CODE UNDER THE Clear Message BUTTTON this.rtDbMsgBox.Text = "";

3. Then, your method should look like this – with the two new lines of code BETWEEN the beginning curly bracket and the ending curly bracket of the method. This code does not do much except clear out any text that might be displayed in the richTextBox (which you) named “ txtDBMsgBox”. “this” just means the form that you are designing.

private void button1_Click(object sender, EventArgs e) {

// THIS IS THE CODE UNDER THE Clear Message BUTTTON this.rtDbMsgBox.Text = "";

}

4. To Run your form,

From Visual Studio’s menu, click on Debug – Start Debugging (or just press the F5 key). If it says “There are errors do you want to run anyway?”, SAY NO and

o Check out the errors at the bottom of the screen. o If you double click on the error message, it will position your cursor at the place in your source

code where the error is.o Most likely you did not name the richTextbox exactly “rtDbMsgBox” (and it does care about

capital versus small case). Or, you may have not put your code inside the two curly braces that define the beginning and ending of the button click method. You should probably call your TA over to resolve this.

o When you fix all errors and run your program again (F5), a form should come up (in its own window).

o There is really no code under the buttons yet to test, so at this point, we are just checking to make sure that there are no errors and your form is able to run.

o Then close out the form window. You cannot modify the form’s code WHILE it is still running.

17

Page 18: Temple Universitycis-linux2.temple.edu/~sallyk/tutorials_SQL_Server/SQLSV…  · Web viewCreating Stored Procedures & Triggers (Sql Mgt Studio 2005) Accessing a Data Base from a

5. Next (back in Visual Studio’s design mode), double click on the “Show Data” button, and paste the code below INSIDE that button click method (BETWEEN the beginning curly bracket and the ending curly bracket of the method). MAKE SURE TO INCLUDE THE COMMENT AT THE TOP that identifies what code this is.

// THIS IS THE CODE UNDER THE “SHOW DATA” BUTTTON // Clear values on form, if there are any. this.rtShowDataBox.Text = ""; this.rtDbMsgBox.Text = "";

// Specify the sql database you want to connect with SqlConnection conn = new SqlConnection("Data Source=DWARF;" + "Initial Catalog=sp09_c21090215;" + "User ID=sp09_c21090215;Password=cynhvyg3");

try // We must put database code inside a try block so that an exception is thrown if things go wrong. // If an exception is thrown inside a try block, we can handle the situation nicely – in the matching catch block.

{

// open the database connection conn.Open();

// Put the SQL (that we want to run) into a string variable. string sqlStatement = "SELECT employee_id, employee_name FROM my_employee ORDER BY employee_id";

// create a SqlCommand object (give it the SQL statement & the DB connection) SqlCommand command = new SqlCommand(sqlStatement, conn);

// execute the command – it returns a “SqlDataReader” object which holds the result set SqlDataReader reader = command.ExecuteReader();

// display the results – (The Read method returns the next row in the result set) while (reader.Read()) { this.rtShowDataBox.Text += reader["employee_id"].ToString() + " - "; this.rtShowDataBox.Text += reader["employee_name"].ToString() + "\r\n"; }

// close the database connection reader.Close(); conn.Close(); }

// The “catch block” only runs if there’s a problem. We display the error message & close the DB connection catch (Exception ex) { this.rtDbMsgBox.Text = ex.Message; conn.Close(); }

18

Page 19: Temple Universitycis-linux2.temple.edu/~sallyk/tutorials_SQL_Server/SQLSV…  · Web viewCreating Stored Procedures & Triggers (Sql Mgt Studio 2005) Accessing a Data Base from a

6. At the very top of the Form code, you’ll see some using statements that look like the ones below. You need to add the last using statement (shown in large font). TYPE THIS IN – do not copy/paste. Order does not matter, but you can put your using statement after theirs and maybe with a blank line ahead of it so you know that you entered this using statement. Case matters (so capitalize what is capitalized in the sample code). Type slowly and take advantage of Visual Studio’s “intelli-sense” (typing look-ahead – select values from the list instead of typing or copy/pasting them) – this way you know that what you are entering is valid.

using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Windows.Forms;

using System.Data.SqlClient; // You must type this in at top of form code

D. RUN YOUR PROGRAM

To run your program: From Visual Studio’s menu, click on Debug – Start Debugging (F5). If it says “There are errors do you want to run anyway?”, SAY NO and

o Check out the errors at the bottom of the screen. Maybe you did not name one of your form controls properly – that would cause an error.

o If you double click on the error message, it will position your cursor at the place in your source code where the error is.

o Usually, you just fix the first error and run again since one error can cause many other errors below it. o When you fix all errors and run your program again (F5), a form should come up (in its own window).

When the Form comes up (in its own Window):

Click on the “Show Data” button. If all went well, your form should display the employee names and IDs from your database. If not, you should see an error message displayed on the form. If you are not sure how to fix the error, ask your TA for help.

Close out the window that holds your program. You can’t modify the program while it is running, so always remember to close out the window that your program runs in before you switch back to VS to edit your program.

19

Page 20: Temple Universitycis-linux2.temple.edu/~sallyk/tutorials_SQL_Server/SQLSV…  · Web viewCreating Stored Procedures & Triggers (Sql Mgt Studio 2005) Accessing a Data Base from a

E. ADD CODE TO INSERT DATA (USING “PLAIN SQL” METHOD)

In this step, you will add code to INSERT data to the Database (using the “Plain SQL” method) and then run that code.

Back in the Form Design screen, Double click on the “Insert– Plain SQL” button. Paste the following code into that button click event (including the top comment so you will know which

button is which when you are reading the code). Again, make sure that you paste the code BETWEEN the button click method’s beginning and ending curly

brackets .

// THIS IS THE CODE UNDER THE “Insert – Plain SQL” BUTTTON // Clear values on form, if there are any. this.rtShowDataBox.Text = ""; this.rtDbMsgBox.Text = "";

// Specify the sql database you want to connect with SqlConnection conn = new SqlConnection("Data Source=DWARF;" + "Initial Catalog=sp09_c21090215;" + "User ID=sp09_c21090215;Password=cynhvyg3");

int numRowsAffected = -999; // dummy value

try { // open the connection conn.Open();

// Build the SQL statement that you want to run // -- mixing SQL syntax with values from the form. string sqlStatement = "INSERT into my_employee (employee_id, employee_name) values (" + this.txtEmp_ID.Text + ", " + "'" + this.txtEmpName.Text + "')";

// Display (on form) the sql statement that will be run -- “\r\n” just inserts a newline into the message this.rtDbMsgBox.Text = "SQL: " + sqlStatement + "\r\n";

// Execute the sql statement and see how many rows are affected SqlCommand command = new SqlCommand(sqlStatement,conn); numRowsAffected = command.ExecuteNonQuery();

// Display (on form) the results -- how many rows were affected this.rtDbMsgBox.Text += System.Convert.ToSingle(numRowsAffected) + " row(s) affected !!"; // close the connection conn.Close(); } catch (Exception ex) { this.rtDbMsgBox.Text = ex.Message; conn.Close(); }

Run your program as before:

20

Page 21: Temple Universitycis-linux2.temple.edu/~sallyk/tutorials_SQL_Server/SQLSV…  · Web viewCreating Stored Procedures & Triggers (Sql Mgt Studio 2005) Accessing a Data Base from a

Click on Debug – Start Debugging (F5). If it says there are errors do you want to run anyway – SAY NO !!! check out the errors at the bottom of

the screen and ask for help.

When the form comes up, Click on the “Show Data” button and take note of what data is currently in the database. Type in a (new) employee id and employee name (remember the number can’t be a repeat of what’s

already in the database). Click on the “Insert - Plain SQL” button. In the richTextBox on the upper right of the form, you should see a message that shows the actual INSERT

statement that your code built followed by (assuming the insert was successful), “1 row affected”. Then click on the “Show Data” button again. Hopefully, you will see the employee data that you just

added. Enter several more employee records, trying to see what kinds of error messages you can get, e.g.,

duplicate primary key, non-number for employee id, employee name that is longer than 20 characters, empty employee id, empty employee name (this might be accepted because spaces are not NULL). Any error messages will be displayed in the upper right textbox on your form.

Try entering a name that has a single quote in it, like “Sally’s Great”. You should see an error message like:Incorrect syntax near 's'. Unclosed quotation mark after the character string ')'.

Can you guess why you get this message? Close out your employee form. (You can’t modify the program while it is running, so always remember to

close out the window that your program runs in before you switch back to VS to edit your program.)

21

Page 22: Temple Universitycis-linux2.temple.edu/~sallyk/tutorials_SQL_Server/SQLSV…  · Web viewCreating Stored Procedures & Triggers (Sql Mgt Studio 2005) Accessing a Data Base from a

F. ADD CODE TO INSERT DATA (USING “STORED PROCEDURE” METHOD)

In this step, you will add code to INSERT data to the Database (using the “Stored Procedure” method) and then run that code.

Back in the Form Design screen, double click on the “Insert– Stored Procedure” button. Paste the following code into that button click event -- paste the code BETWEEN the method’s curly brackets.

// THIS IS THE CODE UNDER THE “Insert – Stored Procedure” BUTTTON // Clear values on form, if there are any. this.rtShowDataBox.Text = ""; this.rtDbMsgBox.Text = "";

// Specify the sql database you want to connect with SqlConnection conn = new SqlConnection("Data Source=DWARF;" + "Initial Catalog=sp09_c21090215;"

+ "User ID=sp09_c21090215;Password=cynhvyg3");

int returnCode = -999; // dummy value try { conn.Open(); // open the connection

// Specify the name of the Stored Procedure you will call string SP_Name = "insert_employee";

// Create the SQL Command object and specify that this is a SP. SqlCommand command = new SqlCommand(SP_Name, conn); command.CommandType = CommandType.StoredProcedure; // Specify values for the two input parameters of our Stored Procedure (insert_employee) // Parameters MUST be named the same as the parameters defined in the Stored Procedure. command.Parameters.AddWithValue("@myemp_id", System.Convert.ToInt32(this.txtEmp_ID.Text)); command.Parameters.AddWithValue("@myemp_name", this.txtEmpName.Text);

// Display the sql statement that will be run (on form) this.rtDbMsgBox.Text = "Stored Procedure Name: " + SP_Name + "\r\n";

// Execute the sql statement and see how many rows are affected returnCode = command.ExecuteNonQuery();

this.rtDbMsgBox.Text = "It worked-No exception was thrown"; conn.Close(); // close the connection }

catch (Exception ex) { this.rtDbMsgBox.Text = ex.Message; conn.Close(); } }

Run your program as before:

22

Page 23: Temple Universitycis-linux2.temple.edu/~sallyk/tutorials_SQL_Server/SQLSV…  · Web viewCreating Stored Procedures & Triggers (Sql Mgt Studio 2005) Accessing a Data Base from a

Click on Debug – Start Debugging (F5). If it says there are errors do you want to run anyway – SAY NO !!! check out the errors at the bottom of

the screen and ask for help.

When the form comes up,

Click on the “Show Data” button so you can see what data is there to start with. Type in a (new) employee id and employee name. Click on the “Insert – Stored Procedure” button. If all went well, you should see a message in the upper right of the form “It worked-No exception was

thrown”. Then click on the “Show Data” button – hopefully, you will see the new employee record you just added. Enter several more employee records, trying to see what kinds of error messages you can get, e.g.,

duplicate primary key, non-number for employee id, employee name that is longer than 20 characters, empty employee id, empty employee name (this might be accepted because spaces are not NULL). Any error messages will be displayed in the upper right textbox on your form.

Try entering a name that has a single quote in it, like “Sally’s Great”. Do you get an error message this time? Why or why not? Click on the Show Data button to see what data was entered.

Close out your employee form. (You can’t modify the program while it is running, so always remember to close out the window that your program runs in before you switch back to VS to edit your program.)

23

Page 24: Temple Universitycis-linux2.temple.edu/~sallyk/tutorials_SQL_Server/SQLSV…  · Web viewCreating Stored Procedures & Triggers (Sql Mgt Studio 2005) Accessing a Data Base from a

G. ADD CODE TO INSERT DATA (USING “PARAMETERIZED SQL” METHOD)

In this step, you will add code to INSERT data to the Database (using the “Parameterized SQL” method) and then run that code.

Back in the Form Design screen, double click on the “Insert - Parameterized SQL” button. Paste the following code into that button click event. Again, make sure that you paste the code BETWEEN the

button click method’s beginning and ending curly brackets. (Include the top comment so you know which method is which, when looking at your code.)

// THIS IS THE CODE UNDER THE “Insert– Parameterized SQL” BUTTTON

// Clear values on form, if there are any. this.rtShowDataBox.Text = ""; this.rtDbMsgBox.Text = "";

// Specify the sql database you want to connect with SqlConnection conn = new SqlConnection("Data Source=DWARF;" + "Initial Catalog=sp09_c21090215;" + "User ID=sp09_c21090215;Password=cynhvyg3");

int numRowsAffected = -999; // dummy value try { conn.Open(); // open the connection

// Put together the SQL that you want to run - but with placeholders where values from the form will be put. string sqlStatement = "INSERT into my_employee (employee_id, employee_name) "+ " values ( @emp_id, @emp_name)";

// Replace the placeholders (in the SQL Statement) with values from the form. Since you are not callinga pre-existing // Stored Procedure, you can name the parameters what you want (as long as it matches the SQL you specified in the line above). SqlCommand command = new SqlCommand(sqlStatement, conn); command.Parameters.AddWithValue("@emp_id",System.Convert.ToInt32(this.txtEmp_ID.Text)); command.Parameters.AddWithValue("@emp_name",this.txtEmpName.Text);

// Display the sql statement that will be run (on form) this.rtDbMsgBox.Text = "SQL: " + sqlStatement + "\r\n";

// Execute the sql statement and see how many rows are affected numRowsAffected = command.ExecuteNonQuery();

this.rtDbMsgBox.Text =+ System.Convert.ToSingle(numRowsAffected) + " rows were affected !!"; conn.Close(); // close the connection } catch (Exception ex) { this.rtDbMsgBox.Text = ex.Message; conn.Close(); }

24

Page 25: Temple Universitycis-linux2.temple.edu/~sallyk/tutorials_SQL_Server/SQLSV…  · Web viewCreating Stored Procedures & Triggers (Sql Mgt Studio 2005) Accessing a Data Base from a

Run your program as before: Click on Debug – Start Debugging (F5). If it says there are errors do you want to run anyway – SAY NO !!! and fix the errors.

When the form comes up, Type in an employee id and employee name. Click on the “Insert – Parameterized SQL” button. Then click on the “Show Data” button – hopefully, you will see the new employee record you just added. Enter several more employee records, trying to see what kinds of error messages you can get. Close out your employee form.

This concludes the Demo part of this lab. BEFORE YOU LEAVE LAB, if you didn’t store your project on your flash drive, then find your project folder on the lab computer’s C Drive flash drive – under “my documents” – “Visual Studio 2008” – Projects – <the name you gave when you created your project>. Copy that whole folder onto your flashdrive – or zip up that folder and email it to yourself. (Make sure to get the folder that is immediately under “Projects” because there is another folder with the same name underneath itself.

Later, to have Visual Studio 2008 to open your project from another computer, copy (or unzip) your project folder onto that new computer, then double click on the “solution file” that is under your project folder (see below).

25

Page 26: Temple Universitycis-linux2.temple.edu/~sallyk/tutorials_SQL_Server/SQLSV…  · Web viewCreating Stored Procedures & Triggers (Sql Mgt Studio 2005) Accessing a Data Base from a

H. COMPARISION OF THE THREE METHODS TO MODIFY A DATABASE

There are pros and cons to each of the 3 different methods that we demonstrated above.

THE “PLAIN” SQL STATEMENT METHOD

The “Plain” SQL statement has these pros and cons.

With this method, your program builds a SQL statement (like the one shown below) in a string variable, then asks SQL Server to execute it.

INSERT INTO my_employee (employee_id, employee_name) VALUES (100, 'JOHN JONES');

This method is perhaps easiest to conceptualize because your program just builds the SQL that you would enter if you were typing into a SQL Query window. As a programmer (when you are debugging your code), you can display the proposed SQL statement on the form to see if it looks right before trying to execute it.

However, this method can be tricky to program – it’s easy to make syntax errors (you have to include single quotes inside double quotes). For example, to generate the SQL shown above, you would need code that looks like this. While I have formatted the single quotes below (different color, larger font) so that you can see them better, but when you are coding, it is easy to forget a single quote (and not notice the error).

string sqlStatement = "INSERT into my_employee (employee_id, employee_name) values (" + this.txtEmp_ID.Text + ", " + "'" + this.txtEmpName.Text + "')";

This method is slow to execute because the DBMS has to “compile” (run a syntax check and translate) the SQL statement every single time it gets executed – because the DBMS assumes this SQL could be anything and it needs to make sure you used the correct SQL keywords in the right order, with proper spelling and punctuation, and that all the table and field names actually exist in this database.

This method is not secure. A clever, malicious user could type “contrived values” into the form and press the button. If the user is lucky (and you are coding the way he thinks you are), he can run malicious SQL against your database, perhaps showing him confidential data or deleting valuable data, etc.

26

Page 27: Temple Universitycis-linux2.temple.edu/~sallyk/tutorials_SQL_Server/SQLSV…  · Web viewCreating Stored Procedures & Triggers (Sql Mgt Studio 2005) Accessing a Data Base from a

THE “STORED PROCEDURE” METHOD

The Stored Procedure method has these pros and cons.

With this method, your program asks SQL Server to execute a Stored Procedure, similar to when you typed the following into a SQL Query window:

EXEC insert_employee @myemp_id = 100, @myemp_name = 'JOHN JONES'

The application programming (e.g., Visual Studio) is easy to understand (once you get used to it) and there is less chance of making a programming error since you do not have to build SQL statements with "'" in them.

string SP_Name = "insert_employee"; SqlCommand command = new SqlCommand(SP_Name, conn); command.CommandType = CommandType.StoredProcedure; command.Parameters.AddWithValue("@myemp_id", System.Convert.ToInt32(this.txtEmp_ID.Text)); command.Parameters.AddWithValue("@myemp_name", this.txtEmpName.Text);

With this method, the programmer must first create all the Stored Procedures in SQL Server. You could need 3 Stored Procedures (one for INSERT, one for UPDATE, and one for DELETE) per table that users will be maintaining through your application.

Another disadvantage is the “tight coupling” between the application program & database programs (the Stored Procedures). The application program needs to use the exact name of each Stored Procedure and the exact name for every input parameter to those Stored Procedures.

This method is secure because the database will not just run “any old SQL” that you build in your program (that has possibly malicious user data embedded in it). Instead, it calls a Stored Procedure which is like a method that expects parameters (and they must be of the correct type) and the SQL that gets run is exactly the SQL that you put in the Stored Procedure (user data cannot be mixed with SQL for malicious purpose).

If the application will ever be migrated to a different DBMS (e.g., Oracle), these SPs will probably need to be rewritten, so this method is not easily “Portable”.

27

Page 28: Temple Universitycis-linux2.temple.edu/~sallyk/tutorials_SQL_Server/SQLSV…  · Web viewCreating Stored Procedures & Triggers (Sql Mgt Studio 2005) Accessing a Data Base from a

THE “PARAMETERIZED SQL STATEMENT” METHOD

The Parameterized SQL statement method may be considered the “best of both worlds”.

With this technique your program invokes a Stored Procedure, except that the Stored Procedure is one that you (the programmers) never had to create. With this method, the Stored Procedures are created automatically by SQL Server (or Oracle) – on your behalf – whenever the DBMS detects that you are running a Parameterized SQL statement that was never run before. The name of the Stored Procedure will not be an understandable one (it will probably be some randomly generated unique number/ID) like this – and it may be hidden from you when you explore the database (e.g., in SQL Mgt Studio).

EXEC AXQ123JIOP @emp_id = 100, @emp_name = 'JOHN JONES'

The code for this method looks like this – it’s easy to read, and not hard to code (not prone to errors since there is no need to embed single quotes inside double quotes).

string sqlStatement = "INSERT into my_employee (employee_id, employee_name) "+ " values ( @emp_id, @emp_name)"; SqlCommand command = new SqlCommand(sqlStatement, conn); command.Parameters.AddWithValue("@emp_id",System.Convert.ToInt32(this.txtEmp_ID.Text)); command.Parameters.AddWithValue("@emp_name",this.txtEmpName.Text);

This method is secure just like the Stored Procedure method – user data is only passed as input parameters to the Stored Procedure, there is no dynamically build SQL to be executed that embeds (possibly malicious) user data in it.

With this method, your application program is not tightly coupled with database programs. That is to say, your application doesn’t need intimate knowledge about all the Stored Procedures (procedure names, parameter names, parameter types). It just uses the Parameterized SQL statements and if the application program changes (e.g., an input parameter type changes), the DBMS considers it a new SP and creates it for you.

This method is more easily ported to another DBMS. If you port your application from one DBMS to another (e.g., SQL Server to Oracle or vice versa), you don’t have to rewrite the Stored Procedures – you never actually wrote them in the first place. You just run your application and the new DBMS will detect any/all of the Parameterized SQL statements that are run and create a Stored Procedure for each one (only the first time it is run)

28

Page 29: Temple Universitycis-linux2.temple.edu/~sallyk/tutorials_SQL_Server/SQLSV…  · Web viewCreating Stored Procedures & Triggers (Sql Mgt Studio 2005) Accessing a Data Base from a

6. HOMEWORK

1. Create a new table in your database. This table should have your name in its table name, e.g., “sally_product”. This table should have an IDENTITY primary key, a character field, and a numeric field (as shown in the sample SQL DDL below):

CREATE TABLE sally_product (product_id INT IDENTITY PRIMARY KEY NOT NULL, product_description CHAR(30) NOT NULL, product_quantity INT DEFAULT 0); 2. Create a Stored Procedure that inserts a new record into this table. Because the PK of this table is an IDENTITY

type field (like Access auto-number), remember not to INSERT into the IDENTITY field. So, for example, the insert statement that would work (for the above table), would look like this:

INSERT INTO sally_product (product_description, product_quantity) VALUES ('Outdoor Grill', 25);

Make sure that your SP works by testing it out from a query window, e.g.,

EXEC insert_sallyProduct @mydesc = 'lawn chair', @myqty = 30

3. Create an update trigger on your new product table. The trigger must track changes to some field within your product table – putting the before value, after value, date/time, and user name into an audit table. You’ll have to create the audit log table first, like you did in lab. (The audit log table also should have your name as part of its table name, e.g., sally_product_log.) Test out your trigger by modifying a couple of values in YOUR product table – make sure the tracking records show up in your audit log table.

4. Create a new Visual Studio C# Windows application – name the project with your name in it (when you create it). Make the form look like the form created in this lab. The button code must access YOUR table in YOUR database.

o This means you have to modify the connect string in the multiple places, wherever it appears.o You have to change all the SQL – to reference YOUR table and column names.

If you want to reuse the project you just created in lab, just back it up (copy the whole project folder), but then use the original project/folder, not the backup one (this becomes more important with Web Apps).

5. SUBMITTING HOMEWORK Create a Word document with the following screen captures taken from SQL Mgt Studio & label each part. (To

get a screen capture, use the Prt-Sc button to copy the screen into the clipboard, then paste into Word). a. A screen capture, showing your product table with some data in it (this is the table you created that has

your name as part of the table name, e.g., Sally_Product) – right click on the table and select Open Table.b. A screen capture of the code you get when you right click on your trigger and select Modify.c. A screen capture showing the data that was inserted into your audit log table (by your trigger) – Open

Table on the audit log table (which should also have your name in its table name). Summarize the pros and cons of the 3 methods you used to insert records into your database. Put the above word document inside your project folder (the project folder that was created by visual studio).

29

Page 30: Temple Universitycis-linux2.temple.edu/~sallyk/tutorials_SQL_Server/SQLSV…  · Web viewCreating Stored Procedures & Triggers (Sql Mgt Studio 2005) Accessing a Data Base from a

Zip up this folder and attach it to the blackboard assignment.

30