Visual C#

Techniques of Commanding a Database

So far, when using a command, we could create a SELECT statement that specified all fields that would be shown in the result. Here is an example:

23 min read4,990 words26 code samples

Parameterizing a SQL Expression#

Introduction#

Overview

C#
SELECT * FROM Students;

We also saw how to select a group of fields that would be shown in the result. Here is an example:

C#
SELECT * FROM Students WHERE ParentsNames IS NOT NULL;

When studying data analysis, we saw how you could let the user specify the value of a particular column so the table or view would display only the result(s) based on that value. Through the magic of data binding, we saw how you could let the user enter the receipt number of a record, then locate and display that record. Instead of performing these operations manually, Transact-SQL, the .NET Framework, and Microsoft Visual Studio provide you all the necessary means of performing the same action (of locating one particular record or a group of records) without writing a single line of code or by following just a few steps. Practical Learning: Introducing Parameterized Statements

  1. Start Microsoft Visual C# and create a new Windows Application named WattsALoan5
  2. In the Solution Explorer, right-click Form1.cs and click Rename
  3. Type Central.cs and press Enter
  4. Double-click the middle of the form and implement the Load event as follows: 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; namespace WattsALoan5 { public partial class Central : Form { public Central() { InitializeComponent(); } void CreateDatabase() { string strWattsALoan = ""; SqlConnection cnnWattsALoan = null; SqlCommand cmdWattsALoan = null; using (cnnWattsALoan = new SqlConnection("Data Source=(local); " + "Integrated Security='SSPI';")) { strWattsALoan = "CREATE DATABASE WattsALoan1"; cmdWattsALoan = new SqlCommand(strWattsALoan, cnnWattsALoan); cnnWattsALoan.Open(); cmdWattsALoan.ExecuteNonQuery(); MessageBox.Show("A database named WattsALoan1 " + "has been created."); } using (cnnWattsALoan = new SqlConnection("Data Source=(local); " + "Database='WattsALoan1'; " + "Integrated Security='SSPI';")) { strWattsALoan = "CREATE TABLE dbo.Employees( " + "EmployeeNumber char(5) NOT NULL, " + "FirstName varchar(20) NULL, " + "LastName varchar(10) NOT NULL, " + "FullName AS ((LastName + ', ') + FirstName), " + "Title varchar(100), " + "HourlySalary money, " + "Username varchar(20), " + "Password varchar(20), " + "CONSTRAINT PK_Employees " + " PRIMARY KEY(EmployeeNumber)); " + "INSERT INTO dbo.Employees(EmployeeNumber, " + "FirstName, LastName, Title, HourlySalary) " + "VALUES('22740', 'Jeanne', 'Tryler', " + "'Accounts Manager', 22.24); " + "INSERT INTO dbo.Employees(EmployeeNumber, " + "FirstName, LastName, Title, HourlySalary) " + "VALUES('40952', 'Helene', 'Gustman', " + "'Accounts Representative', 14.55); " + "INSERT INTO dbo.Employees(EmployeeNumber, " + "FirstName, LastName, Title, HourlySalary) " + "VALUES('84615', 'Ernest', 'Thomas', " + "'Accounts Representative', 12.75); " + "CREATE TABLE dbo.Customers( " + "AccountNumber char(6) NOT NULL, " + "DateCreated varchar(50), " + "CustomerName varchar(50) NOT NULL, " + "BillingAddress varchar(100), " + "BillingCity varchar(50), " + "BillingState varchar(50), " + "BillingZIPCode varchar(10), " + "EmailAddress varchar(100), " + "CONSTRAINT PK_Customers " + " PRIMARY KEY(AccountNumber)); " + "INSERT INTO Customers(AccountNumber, DateCreated, " + "CustomerName, BillingAddress, BillingCity, " + "BillingState, BillingZIPCide, EmailAddress) " + "VALUES('917394', '2/26/2004', 'Julius Ramse', " + "'927 Feuler Ave', 'Silver Spring', " + "'MD', '20904', '[email protected]'); " + "INSERT INTO Customers(AccountNumber, DateCreated, " + "CustomerName, BillingAddress, BillingCity, " + "BillingState, BillingZIPCide) " + "VALUES('862864', '06/22/2006', 'Gertrude Vaillant', " + "'10055 Larsenic Rd', 'Takoma Park', " + "'MD', '20910'); " + "INSERT INTO Customers(AccountNumber, DateCreated, " + "CustomerName, BillingAddress, BillingCity, " + "BillingState, BillingZIPCide, EmailAddress) " + "VALUES('846864', '12/3/2004', 'James Barrouch', " + "'4204 Fallon Drive', 'Silver Spring', " + "'MD', '20906', '[email protected]'); " + "INSERT INTO Customers(AccountNumber, DateCreated, " + "CustomerName, BillingAddress, BillingCity, " + "BillingState, BillingZIPCide) " + "VALUES('248047', '08/02/2006', 'Christine Rougher', " + "'825 Manning Street', 'Alexandria', " + "'VA', '22231'); " + "INSERT INTO Customers(AccountNumber, DateCreated, " + "CustomerName, BillingAddress, BillingCity, " + "BillingState, BillingZIPCide, EmailAddress) " + "VALUES('131804', '10/08/2006', 'Patrick Heller', " + "'2480 Clarington Drive NW', 'Washington', " + "'DC', '20006', '[email protected]'); " + "CREATE TABLE dbo.LoanAllocations( " + "LoanNumber int identity(1000, 1) NOT NULL, " + "DatePrepared varchar(50), " + "EmployeeNumber char(5), " + "AccountNumber char(6), " + "LoanType varchar(50), " + "LoanAmount money NOT NULL, " + "InterestRate decimal(6,2) NOT NULL, " + "Periods decimal(6,2) NOT NULL, " + "InterestAmount money, " + "FutureValue money, " + "MonthlyPayment money, " + "Notes Text, " + "CONSTRAINT PK_LoanAllocations " + " PRIMARY KEY(LoanNumber)); " + "CREATE TABLE dbo.Payments( " + "PaymentID int identity(1000, 1) NOT NULL, " + "PaymentDate datetime NOT NULL, " + "EmployeeNumber char(5), " + "LoanNumber int NOT NULL " + " CONSTRAINT FK_LoanAllocations " + " FOREIGN KEY REFERENCES " + " LoanAllocations(LoanNumber), " + "PaymentAmount money NOT NULL, " + "Balance money, " + "Notes Text, " + "CONSTRAINT PK_Payments " + " PRIMARY KEY(PaymentID));"; SqlCommand cmdTimesheets = new SqlCommand(strWattsALoan, cnnWattsALoan); cnnWattsALoan.Open(); cmdTimesheets.ExecuteNonQuery(); MessageBox.Show("The tables of the WattsALoan " + "database have been created."); } } private void Central_Load(object sender, EventArgs e) { CreateDatabase(); } } }
  5. Execute the application
  6. Close the form and return to your programming environment
  7. In the Data Sources window, click Add New Data Source
  8. In the first page of the wizard, make sure Database is selected and click Next
  9. If you see a WattsALoan1 connection in the combo box, select it. Otherwise, use the New Connection... button and the Add Connection dialog box to create a connection to the WattsALoan1 database
  10. Click Next
  11. Change the connection string to csWattsALoan and click Next
  12. In the list, click the check box of Tables
  13. Change the data set name to dsWattsALoan and click Finish
  14. In the Server Explorer, expand the server .WattsALoan1.dbo connection
  15. Click the + button of Database Diagram
  16. When the message box comes up, read it and click Yes
  17. Right-click Database Diagram and click Add New Diagram...
  18. In the dialog box, double-click each table and, when all tables have been added, click Close
  19. Create the relationships using the common fields
  20. Save the diagram as dgmWattsALoan and close it
  21. To create a new form, on the main menu, click Project -> Add Windows Form...
  22. Set the Name to Customers and click Add
  23. In the Data Sources window, drag Customers and drop it on the Customers form
  24. Under the form, click the objects and, using the Properties window, change their names as follows: Object Name customersBindingSource bsCustomers customersTableAdapter taCustomers customersBindingNavigator bnCustomers
  25. Design the form as follows: Control Text Name Label View Payments For (Enter Loan #): TextBox txtAccountNumber Button Submit btnSubmit Button Close btnClose
  26. Double-click the Submit button and implement its event as follows: private void btnSubmit_Click(object sender, EventArgs e) { bsPayments.Filter = "LoanNumber = '" + txtAccountNumber.Text + "'"; }
  27. Return to the form and double-click the Close button
  28. Implement its even as follows: private void btnClose_Click(object sender, EventArgs e) { Close(); }
  29. Access the Central form, add a button and change its properties as follows: (Name): btnCustomer s Text: Customers...
  30. Double-click the Account Types button and implement its event as follows: private void Central_Load(object sender, EventArgs e) { // CreateDatabase(); } private void btnCustomers_Click(object sender, EventArgs e) { Customers clients = new Customers(); clients.ShowDialog(); }
  31. To create a new form, on the main menu, click Project -> Add Windows Form...
  32. Set the Name to NewLoanAllocation and click Add
  33. Design the form as follows: Control Text Name Other Properties Label Date Prepared: DateTimePicker dtDatePrepared Label Prepared By BackColor: Gray AutoSize: False Label Employee #: MaskedTextBox txtEmployeeNumber Mask: 00000 TextBox txtEmployeeName Label Prepared For BackColor: Gray AutoSize: False Label Account #: MaskedTextBox txtAccountNumber Mask: 000000 TextBox txtCustomerName Label Loan Preparation BackColor: Gray AutoSize: False Label Loan Type ComboBox cbxLoanTypes Items: Other Car Loan Credit Card Personal Loan Furniture Loan Label Loan Amount: TextBox 0.00 txtPresentValue TextAlign: Right Label Interest Rate: TextBox 0.00 txtInterestRae TextAlign: Right Label % Label Number of Months: TextBox 0 txtMonths TextAlign: Right Button Calculate btnCalculate Label Interest Amt: TextBox 0.00 txtInterestAmount TextAlign: Right Label Future Value: TextBox 0.00 txtFutureValue TextAlign: Right Label Monthly Payment: TextBox 0.00 txtMonthlyPayment TextAlign: Right Label Notes BackColor: Gray AutoSize: False TextBox txtNotes Multiline: True ScrollBars: Vertical Button Submit btnSubmit Button Close btnClose
  34. Click the Employee Number text box and, in the Properties window, click the Events button
  35. Double-click the Leave button and implement the event as follows: 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; namespace WattsALoan5a { public partial class NewLoanAllocation : Form { public NewLoanAllocation() { InitializeComponent(); } private void txtEmployeeNumber_Leave(object sender, EventArgs e) { using (SqlConnection cnnWattsALoan = new SqlConnection("Data Source=(local);" + "Database='WattsALoan1';" + "Integrated Security=SSPI;")) { string strSelect = "SELECT FullName FROM Employees " + "WHERE EmployeeNumber = '" + txtEmployeeNumber.Text + "';"; SqlCommand cmdWattsALoan = new SqlCommand(strSelect, cnnWattsALoan); cnnWattsALoan.Open(); SqlDataReader rdrWattsALoan = cmdWattsALoan.ExecuteReader(); while (rdrWattsALoan.Read()) txtEmployeeName.Text = rdrWattsALoan[0].ToString(); } } } }
  36. Return to the form and click the Account Number text box
  37. In the Events section of the Properties window, double-click Leave and implement the event as follows: private void txtAccountNumber_Leave(object sender, EventArgs e) { using (SqlConnection cnnWattsALoan = new SqlConnection("Data Source=(local);" + "Database='WattsALoan1';" + "Integrated Security=SSPI;")) { string strSelect = "SELECT CustomerName FROM Customers " + "WHERE AccountNumber = '" + txtAccountNumber.Text + "';"; SqlCommand cmdWattsALoan = new SqlCommand(strSelect, cnnWattsALoan); cnnWattsALoan.Open(); SqlDataReader rdrWattsALoan = cmdWattsALoan.ExecuteReader(); while (rdrWattsALoan.Read()) txtCustomerName.Text = rdrWattsALoan[0].ToString(); } }
  38. Return to the form and double-click the Calculate button
  39. Implement its event as follows: private void btnCalculate_Click(object sender, EventArgs e) { double Principal = 0.00, InterestRate = 0.00, Periods = 0.00, InterestAmount = 0.00, FutureValue = 0.00, MonthlyPayment = 0.00; try { Principal = double.Parse(txtPresentValue.Text); } catch (FormatException) { MessageBox.Show("Invalid Principal Amount"); } try { InterestRate = double.Parse(txtInterestRate.Text); } catch (FormatException) { MessageBox.Show("Invalid Interest Rate"); } try { Periods = double.Parse(txtMonths.Text); } catch (FormatException) { MessageBox.Show("Invalid Number of Months"); } InterestAmount = Principal * (InterestRate / 100) * Periods / 12; FutureValue = Principal + InterestAmount; MonthlyPayment = FutureValue / Periods; txtInterestAmount.Text = InterestAmount.ToString("F"); txtFutureValue.Text = FutureValue.ToString("F"); txtMonthlyPayment.Text = MonthlyPayment.ToString("F"); }
  40. Return to the form and double-click the Submit button
  41. Implement its even as follows: private void btnSubmit_Click(object sender, EventArgs e) { // Don't save the record if there is no employee number if( txtEmployeeName.Text.Length == 0 ) { MessageBox.Show("You must enter a valid employee number."); return; } // Don't save the record if there is no account number if( txtCustomerName.Text.Length == 0 ) { MessageBox.Show("You must enter a valid account number."); return; } // Make sure the user has specified the type of loan if( cbxLoanTypes.Text.Length == 0 ) { MessageBox.Show("You must specify the type of loan."); return; } // Don't save the record if there is principal if( txtPresentValue.Text.Length == 0 ) { MessageBox.Show("You must specify the amount " + "that is being lent."); return; } // Don't save the record if there is principal if( txtInterestRate.Text.Length == 0 ) { MessageBox.Show("You must specify the interest rate of the loan."); return; } // Don't save the record if there is principal if( txtMonths.Text.Length == 0 ) { MessageBox.Show("You must specify the number " + "of months as period of the loan."); return; } // Before saving the loan, just in case, perform the calculation btnCalculate_Click(sender, e); using( SqlConnection cnnWattsALoan = new SqlConnection("Data Source=(local);" + "Database='WattsALoan1';" + "Integrated Security=SSPI;") ) { string strInsert = "INSERT INTO LoanAllocations( " + "DatePrepared, EmployeeNumber, AccountNumber, " + "LoanType, LoanAmount, InterestRate, Periods, " + "InterestAmount, FutureValue, MonthlyPayment, " + "Notes) VALUES('" + dtpDatePrepared.Value.ToString("d") + "', '" + txtEmployeeNumber.Text + "', '" + txtAccountNumber.Text + "', '" + cbxLoanTypes.Text + "', " + txtPresentValue.Text + ", " + txtInterestRate.Text + ", " + txtMonths.Text + ", " + txtInterestAmount.Text + ", " + txtFutureValue.Text + ", " + txtMonthlyPayment.Text + ", '" + txtNotes.Text + "');"; SqlCommand cmdWattsALoan = new SqlCommand(strInsert, cnnWattsALoan); cnnWattsALoan.Open(); cmdWattsALoan.ExecuteNonQuery(); MessageBox.Show("A new loan has been created."); } // Reset the form dtpDatePrepared.Value = DateTime.Today; txtEmployeeNumber.Text = ""; txtEmployeeName.Text = ""; txtAccountNumber.Text = ""; txtCustomerName.Text = ""; cbxLoanTypes.SelectedIndex = 0; txtPresentValue.Text = "0.00"; txtInterestRate.Text = "0.00"; txtMonths.Text = "0"; txtInterestAmount.Text = "0.00"; txtFutureValue.Text = "0.00"; txtMonthlyPayment.Text = "0.00"; txtNotes.Text = ""; }
  42. Return to the form and double-click the Close button
  43. Implement its even as follows: private void btnClose_Click(object sender, EventArgs e) { Close(); }
  44. Access the Central form, add a button and change its properties as follows: (Name): btnNewLoanAllocation Text: New Loan Allocation...
  45. Double-click the Loan Allocations button and implement its event as follows: private void btnNewLoanAllocation_Click(object sender, EventArgs e) { NewLoanAllocations loan = new NewLoanAllocation(); loan.ShowDialog(); }
  46. Execute the application and open the Loan Allocations form
  47. Create a few loans
  48. Close the forms and return to your programming environment

A Parameterized Statement#

A SQL statement is referred to as parameterized if it would expect an external value in order to be complete. The statement starts like a normal SELECT operation with a WHERE clause. Here is an example:

C#
SELECT * FROM Students WHERE Sex = 'male';

Instead of specifying the value of the column(s) in the WHERE clause, you can wait for the user to do so. This is also referred to as a parameterized query. To create a parameterized statement in the Table window, in the Criteria section, click the box under the Filter column corresponding to the field that holds the value, type @ followed by a variable name. Here is an example:

If you are manually writing a SELECT expression, replace the value with the name of the variable starting with @. Here is an example (we have already studied everything else in this code):

C#
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;

namespace Rosh1
{
    public partial class StudentIdentification : Form
    {
	string strConnection = "Data Source=(local);" +
			       "Database='ROSH';" +
			       "Integrated Security='SSPI';";
	string strStatement = "SELECT StudentNumber, LastName, " +
			      "FirstName, City, State " +
			      "FROM Students " +
			      "WHERE StudentNumber = @StdNbr;";

	public StudentIdentification()
	{
	    InitializeComponent();
	}

	private void btnSubmit_Click(object sender, EventArgs e)
	{
	    using (SqlConnection cnnStudents =
		new SqlConnection(strConnection))
	    {
		SqlCommand cmdStudents = new SqlCommand(strStatement,
						        cnnStudents);

		cnnStudents.Open();
	    }
	}  
    }
}

You can also use a parameterized statement for a Windows application. To create it, after adding a data source to your application, you can open the DataSet in the Designer. Right-click the title bar of the table that holds the columns and click Configure... In the Query Builder, select the table(s) followed the columns that will be used. In the Criteria section of the window, click the Filter box that corresponds to the column on which the parameter will be applied and type @ followed by the name of a variable. Here is an example:

After specifying the parameter, you can click OK

If you click Next, the TableAdapter Configuration Wizard would indicate the methods that would be created:

You can then accept the options, click Next, and click Finish:

Executing a Parameterized Statement#

After creating a parameterized statement, you can test and/or use it. If you had created the statement in the Table window, when you run the query, the SQL interpreter would request a value for the column. If you create the statement in the Object Explorer in Microsoft SQL Server Management Studio or in the Server Explorer of Microsoft Visual Studio, when you execute the statement, a dialog box would come up, asking you to enter a value for the filtered field:

You can then type the appropriate value and click OK (or press Enter). If you use a parameterized statement on a Windows form, the designer would have equipped the form with a text box and a button. You can type the value in that box and click the button. The controls on the form would then be filled with the values related. Here is an example:

Introduction to the Parameters of a Command#

Consider the following class:

C#
public class Calculations
{
    public Return CalculateTriangleArea(double Base, double Height)
    {
    }
}

To calculate the area of a triangle, we need the base and the height. As always in mathematics, there is not a single way of solving this problem. We could declare the method to return a double value:

C#
public class Calculations
{
    public double CalculateTriangleArea(double Base, double Height)
    {
    }
}

Another solution is to declare the method as void but pass an argument by reference:

C#
public class Calculations
{
    public void CalculateTriangleArea(double Base, double Height, out double Area)
    {
    }
}

Like a method, a database command can accept one or more arguments, referred to as parameters. This allows the command to serve as an intermediary between an object of the database, such as a table, a view, a function, or a stored procedure, and the user. To support the parameters passed to a command, the .NET Framework provides a class for each type of connection. The class used for a SQL connection is called SqlParameter. SqlParameter is based on the DbParameter class and it implements the IDbParameter, the IDadaParameter, and the IClonable interfaces. The DbParameter class is defined in the System.Data.Common namespace. Like a method, a command can take more than one parameter. Unlike a method, the parameters passed to a command must be stored in a collection. To support a group of parameters, the .NET Framework provides a collection class for each type of connection. For a SQL connection, the class is called SqlParameterCollection. The SqlParameterCollection class implements the IDataParameterCollection, the IList, the ICollection, and the IEnumerable interfaces. To be able to receive one or more parameters, the command classes are equipped with a property named Parameters which is of the type of the collection (as mentioned already, the name of the class depends on the type of database or collection).

The Parameters of a Command#

Introduction#

In order to pass a parameter to a command, you must build it, which is done in various steps. As mentioned already, a parameter is an object of type SqlParameter. Therefore, to start, you can declare a variable of type SqlParameter but this is only an option (you can pass a parameter directly to a command). To assist you with declaring a variable, the parameter class is equipped with various constructors. The default constructor allows you to declare the variable without giving much information. Here is an example of using it:

C#
private void btnSubmit_Click(object sender, EventArgs e)
{
    using (SqlConnection cnnStudents =
	new SqlConnection(strConnection))
    {
	SqlCommand cmdStudents = new SqlCommand(strStatement,
						        cnnStudents);

	SqlParameter prmStudent = new SqlParameter();

	cnnStudents.Open();
    }
}

After creating the parameter, you must pass it to the command object. As mentioned already, a command has a property named Parameters that is from a class that implements the IList interface. This allows you to call its Add() method to add the parameter. The Add() method comes in various versions. One of the versions allows you to pass a parameter object. Here is an example:

C#
private void btnSubmit_Click(object sender, EventArgs e)
{
    using (SqlConnection cnnStudents =
	new SqlConnection(strConnection))
    {
	SqlCommand cmdStudents = new SqlCommand(strStatement,
						        cnnStudents);

	SqlParameter prmStudent = new SqlParameter();

	cmdStudents.Parameters.Add(prmStudent);

	cnnStudents.Open();
	SqlDataReader rdrStudents = cmdStudents.ExecuteReader();
    }
}

We will review other versions of this method as we move on.

The Name of a Parameter#

Before passing a parameter to a command, you must specify the name of the parameter. To support this, the parameter class is equipped with a property named ParameterName. To specify the name of the argument, assign it to this property. Here is an example of using it:

C#
private void btnSubmit_Click(object sender, EventArgs e)
{
    using (SqlConnection cnnStudents =
	new SqlConnection(strConnection))
    {
	SqlCommand cmdStudents = new SqlCommand(strStatement,
						        cnnStudents);

	SqlParameter prmStudent = new SqlParameter();

	prmStudent.ParameterName = "@StdNumber";

	cmdStudents.Parameters.Add(prmStudent);

	cnnStudents.Open();
	SqlDataReader rdrStudents = cmdStudents.ExecuteReader();
    }
}

An alternative is to declare a parameter variable using a constructor other than the default. As we will see in future sections, the name of the argument is passed as the first argument to the constructor. You may remember that, in C#, when calling a method that takes an argument, you must provide it (the argument). You can pass a value to the method. Here is an example:

C#
using System;

namespace Geometry2
{
    public class Calculations
    {
	public double CalculateSquareArea(double Side)
	{
	    return Side * Side;
	}

	public void ShowResults()
	{
	    CalculateSquareArea(15.68);
	}
    }
}

You can also pass the argument using a name. Here is an example:

C#
using System;

namespace Geometry2
{
    public class Calculations
    {
	public double CalculateSquareArea(double Side)
	{
	    return Side * Side;
	}

	public void ShowResults()
	{
	    double s = 15.68;

	    CalculateSquareArea(s);
	}
    }
}

As a result, the connection string will be visible within the field.

C#
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;

namespace Rosh1
{
    public partial class StudentIdentification : Form
    {
	string strConnection = "Data Source=(local);" +
			       "Database='ROSH';" +
			       "Integrated Security='SSPI';";
    	string strStatement  = "SELECT StudentNumber, LastName, " +
			       "FirstName, City, State " +
			       "FROM Students " +
			       "WHERE StudentNumber = @StdNbr;";

	public StudentIdentification()
	{
	    InitializeComponent();
	}

	private void btnSubmit_Click(object sender, EventArgs e)
	{
	    using (SqlConnection cnnStudents =
		new SqlConnection(strConnection))
	    {
		SqlCommand cmdStudents = new SqlCommand(strStatement, 
							cnnStudents);

		SqlParameter prmStudent = new SqlParameter();

		prmStudent.ParameterName = "@StdNbr";

		cmdStudents.Parameters.Add(prmStudent);

		cnnStudents.Open();
	    }
	}
    }
}

The Type of Parameter#

As you should know from your knowledge of C#, when calling a method that takes an argument, you must pass the argument of the appropriate type. In the same way, a command requires that you specify the type of argument you are passing. To assist you with this, the parameter class is equipped with a property named DbType. The DbType property is of type DbType. This class provides various data types that correspond to the data types of Transact-SQL. To specify the data type of a parameter, access the DbType property of your parameter variable. Assign it the corresponding data type accessed as a static field of the DbType class. Here is an example:

C#
private void btnSubmit_Click(object sender, EventArgs e)
{
    using (SqlConnection cnnStudents =
	new SqlConnection(strConnection))
    {
	SqlCommand cmdStudents = new SqlCommand(strStatement,
						        cnnStudents);

	SqlParameter prmStudent = new SqlParameter();

	prmStudent.ParameterName = "@StdNumber";
	prmStudent.DbType = DbType.String;

	cmdStudents.Parameters.Add(prmStudent);

	cnnStudents.Open();
    }
}

Instead of specifying the data type from the DbType property, you can use the following constructor of the SqlParameter class:

C#
public SqlParameter(string parameterName, SqlDbType dbType);

The first argument to this constructor is the name of the parameter. The second parameter is the data type:

C#
private void btnSubmit_Click(object sender, EventArgs e)
{
    using (SqlConnection cnnStudents =
	new SqlConnection(strConnection))
    {
	SqlCommand cmdStudents = new SqlCommand(strStatement,
						        cnnStudents);

	SqlParameter prmStudent = new SqlParameter("@StdNbr", DbType.String;);

	cmdStudents.Parameters.Add(prmStudent);

	cnnStudents.Open();
    }
}

The Value of a Parameter#

In order to produce a result from a parameterized SQL statement, you must provide the value that the command will apply. To support this, the parameter class is equipped with a property named Value. This value is of type object, which means it is your responsibility to provide the appropriate value for the parameter. Here is an example:

C#
private void btnSubmit_Click(object sender, EventArgs e)
{
    using (SqlConnection cnnStudents =
	new SqlConnection(strConnection))
    {
	SqlCommand cmdStudents = new SqlCommand(strStatement,
						        cnnStudents);

	SqlParameter prmStudent = new SqlParameter();

	prmStudent.ParameterName = "@StdNumber";
	prmStudent.DbType = DbType.String;
	prmStudent.Value = "723897";

	cmdStudents.Parameters.Add(prmStudent);

	cnnStudents.Open();
    }
}

Of course if the value is a number, you can assign it as such. If the user will provide the value from a control, you can access the value of that control and assign it to the Value property. Here is an example:

C#
private void btnSubmit_Click(object sender, EventArgs e)
{
    using (SqlConnection cnnStudents =
	new SqlConnection(strConnection))
    {
	SqlCommand cmdStudents = new SqlCommand(strStatement,
						        cnnStudents);

	SqlParameter prmStudent = new SqlParameter();

	prmStudent.ParameterName = "@StdNumber";
	prmStudent.DbType = DbType.String;
	prmStudent.Value = txtStudentNumber.Text;

	cmdStudents.Parameters.Add(prmStudent);

	cnnStudents.Open();
    }
}

After providing all the information required by the command and adding the parameter to the Parameters collection, you can execute the command to retrieve its values and use them as you see fit. Here is an example:

C#
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;

namespace Rosh1
{
    public partial class StudentIdentification : Form
    {
	string strConnection =  "Data Source=(local);" +
				"Database='ROSH';" +
				"Integrated Security='SSPI';";
	string strStatement = 	"SELECT StudentNumber, LastName, " +
				"FirstName, Sex, City, State " +
				"FROM Students " +
				"WHERE StudentNumber = @StdNbr;";

	public StudentIdentification()
	{
	    InitializeComponent();
	}

	private void btnSubmit_Click(object sender, EventArgs e)
	{
	    using (SqlConnection cnnStudents =
	    	new SqlConnection(strConnection))
	    {
		SqlCommand cmdStudents = 
		    new SqlCommand(strStatement, cnnStudents);

		SqlParameter prmStudent = new SqlParameter();
		prmStudent.ParameterName = "@StdNbr";
		prmStudent.DbType = DbType.String;
		prmStudent.Value = txtStudentNumber.Text;
		cmdStudents.Parameters.Add(prmStudent);

		cnnStudents.Open();
		SqlDataReader rdrStudents = cmdStudents.ExecuteReader();

		while (rdrStudents.Read())
		{
		    txtLastName.Text = rdrStudents[1].ToString();
		    txtFirstName.Text = rdrStudents[2].ToString();
		    txtCity.Text = rdrStudents[3].ToString();
		    txtState.Text = rdrStudents[4].ToString();
		}
	    }
	}

	private void btnClose_Click(object sender, EventArgs e)
	{
	    Close();
	}
    }
}

The Parameters of a Stored Procedure#

Introduction#

Although commands can benefit from parameters, the primary use of parameters is on stored procedures. This is because stored procedures can receive arguments, either or both by value and/or by reference. Before using a stored procedure in a command, obviously you must first create it. It could be as simple as selecting one or a few columns of a table or a view. From the previous lesson, we saw the following example:

C#
CREATE PROCEDURE GetStudentIdentification
AS
BEGIN
    SELECT FirstName, LastName, DateOfBirth, Sex
    FROM Students
END

Practical Learning: Creating a Stored Procedure

  1. Display the Central form and double-click an unoccupied area of its body
  2. Create a new stored procedure as follows: void CurrentBalanceCalculator() { using(SqlConnection cnnWattsALoan = new SqlConnection("Data Source=(local); " + "Database='WattsALoan1'; " + "Integrated Security='SSPI';")) { // Here is how we will evaluate the current balance of an account // Get the amount that was lent to the customer // If the customer had already made at least one payment, // get the current balance of the customer's account // If the customer has never made a payment (yet), // to specify the balance, subtract the current payment // from the original amount of the loan // If the customer had already made at least one payment, // subtract the current payment from the previous balance string strWattsALoan = "CREATE PROCEDURE SpecifyCurrentBalance " + " @PmtDate datetime, " + " @EmplNbr char(5), " + " @LoanNbr int, " + " @PmtAmt money, " + " @Comments Text = '' " + "AS " + "BEGIN " + " DECLARE @AmountOfLoan money; " + " SET @AmountOfLoan = (SELECT las.FutureValue " + " FROM LoanAllocations las " + " WHERE (las.LoanNumber = @LoanNbr)); " + " DECLARE @CurrentBalance money; " + " SET @CurrentBalance = (SELECT MIN(pay.Balance) " + " FROM Payments pay " + " WHERE (pay.LoanNumber = @LoanNbr)); " + " IF @CurrentBalance IS NULL " + " BEGIN " + " INSERT INTO Payments(PaymentDate, EmployeeNumber, " + " LoanNumber, PaymentAmount, " + " Balance, Notes) " + " VALUES(@PmtDate, @EmplNbr, @LoanNbr, @PmtAmt, " + " @AmountOfLoan - @PmtAmt, @Comments); " + " } " + " ELSE " + " BEGIN " + " INSERT INTO Payments(PaymentDate, EmployeeNumber, " + " LoanNumber, PaymentAmount, " + " Balance, Notes) " + " VALUES(@PmtDate, @EmplNbr, @LoanNbr, " + " @PmtAmt, @CurrentBalance - @PmtAmt, @Comments); " + " } " + "END;"; SqlCommand cmdWattsALoan = new SqlCommand(strWattsALoan, cnnWattsALoan); cnnWattsALoan.Open(); cmdWattsALoan.ExecuteNonQuery(); MessageBox.Show("A new stored procedure has been created."); } } private void Central_Load(object sender, EventArgs e) { // CreateDatabase(); CurrentBalanceCalculator(); }
  3. Execute the application
  4. Close the form and return to your programming environment

The Type of Command#

There are a SQL statement and two types of objects a command object can process. When using a command, before executing it, you must specify its type of action. To assist you with this, the command class is equipped with a property named CommandType. The CommandType property is based on the CommandType enumeration. One of the members of the CommandType enumeration is Text. This is applied for a regular SELECT operation and this is the default type used by the command. This means that if you do not specify the type, Text is applied. That has been the case for all the commands (SELECT statements and functions) we have used in previous sections and lessons. Still, if you want to specify that you are using a regular SQL statement for your action, select Text as the CommandType and assign it to the CommandType property. Here is an example:

C#
private void btnSubmit_Click(object sender, EventArgs e)
{
    using (SqlConnection cnnStudents =
	new SqlConnection(strConnection))
    {
	SqlCommand cmdStudents = new SqlCommand(strStatement, cnnStudents);
	cmdStudents.CommandType = CommandType.Text;

	SqlParameter prmStudent = new SqlParameter();
	cmdStudents.CommandType = CommandType.Text;
	prmStudent.ParameterName = "@StdNbr";
	prmStudent.DbType = DbType.String;
	prmStudent.Value = txtStudentNumber.Text;

	cmdStudents.Parameters.Add(prmStudent);

	cnnStudents.Open();

	SqlDataReader rdrStudents = cmdStudents.ExecuteReader();

	while (rdrStudents.Read())
	{
	    txtLastName.Text = rdrStudents[1].ToString();
	    txtFirstName.Text = rdrStudents[2].ToString();
	    txtCity.Text = rdrStudents[3].ToString();
	    txtState.Text = rdrStudents[4].ToString();
	}
    }
}

Because a function is treated like a SELECT statement, if you using it to select some columns, its type is also the Text value. For example, imagine you had created a function as follows:

C#
CREATE FUNCTION dbo.GetFullName
(
    @FName varchar(20),
    @LName varchar(20)
)
RETURNS varchar(41)
AS
    BEGIN
	RETURN @LName + ', ' + @FName;
    };

You can call it as follows:

C#
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;

namespace Rosh1
{
    public partial class StudentFullName : Form
    {
	public StudentFullName()
	{
	    InitializeComponent();
	}

	private void btnSubmit_Click(object sender, EventArgs e)
	{
	    string strConnection = "Data Source=(local);" +
				   "Database='ROSH';" +
				   "Integrated Security='SSPI';";
	    string strStatement  = "SELECT dbo.GetFullName('" +
				   txtFirstName.Text + "', '" +
				   txtLastName.Text + "');";

	    using (SqlConnection cnnStudents =
		new SqlConnection(strConnection))
	    {
		SqlCommand cmdStudents = new SqlCommand(strStatement, cnnStudents);
		cmdStudents.CommandType = CommandType.Text;

		cnnStudents.Open();
		SqlDataReader rdrStudents = cmdStudents.ExecuteReader();

		while (rdrStudents.Read())
		    txtFullName.Text = rdrStudents[0].ToString();
	    }
	}
    }
}

Another member of the CommandType enumeration is named TableDirect. This member can be applied if you are using an OLE DB connection.

Executing a Parameterized Stored Procedure#

If you are planning to use a stored procedure, the CommandType enumeration supports it through the StoredProcedure member. When declaring a command variable, you can pass the name of the stored procedure as the first argument. Here is an example:

C#
private void btnLoad_Click(object sender, EventArgs e)
{
    using (SqlConnection cnnStudents =
	new SqlConnection("Data Source=(local);" +
			  "Database='ROSH';" +
			  "Integrated Security='SSPI';"))
    {
	SqlCommand cmdStudents = new SqlCommand("GetStudentIdentification", cnnStudents);

	cmdStudents.CommandType = CommandType.StoredProcedure;

	cnnStudents.Open();
    }
}

Alternatively, if you declare the command variable using its default constructur, you can access its CommandText property and assign the name of the stored procedure to it. Here is an example:

C#
private void btnLoad_Click(object sender, EventArgs e)
{
    using (SqlConnection cnnStudents =
	new SqlConnection("Data Source=(local);" +
			  "Database='ROSH';" +
			  "Integrated Security='SSPI';"))
    {
	SqlCommand cmdStudents = new SqlCommand();

	cmdStudents.CommandText = "GetStudentIdentification;";
	cmdStudents.Connection = cnnStudents;

	cmdStudents.CommandType = CommandType.StoredProcedure;

	cnnStudents.Open();
    }
}

Once the command is ready, you can execute it. If the stored procedure contains a simple or normal SELECT statement, you can retrieve its values and use them as you see fit, such as displaying them in data grid view. Here is an example:

C#
private void btnLoad_Click(object sender, EventArgs e)
{
    using (SqlConnection cnnStudents =
	new SqlConnection("Data Source=(local);" +
			  "Database='ROSH';" +
			  "Integrated Security='SSPI';"))
    {
	SqlCommand cmdStudents = new SqlCommand("GetStudentIdentification",
						 cnnStudents);
	cmdStudents.CommandType = CommandType.StoredProcedure;


	cnnStudents.Open();
	SqlDataAdapter sdaStudents = new SqlDataAdapter(cmdStudents);
	DataSet dsStudents = new DataSet("StudentsSet");

	sdaStudents.Fill(dsStudents);
	dgvStudents.DataSource = dsStudents;
	dgvStudents.DataMember = dsStudents.Tables[0].TableName;
    }
}

When it comes to parameters of a stored procedure, if you have one that takes arguments, follow the same rules we reviewed earlier for the commands, except that if the argument has a default value, you can omit specifying its value. Practical Learning: Executing an Argumentative Procedure

  1. To create a new form, on the main menu, click Project -> Add Windows Form...
  2. Set the Name to NewPayment and click Add
  3. Design the form as follows: Control Text Name Other Properties Label Payment Date: DateTimePicker dtPaymentDate Label Received By BackColor: Gray AutoSize: False Label Employee #: MaskedTextBox txtEmployeeNumber Mask: 00000 TextBox txtEmployeeName Label Payment For BackColor: Gray AutoSize: False Label Loan #: TextBox txtLoanNumber Label Payment Amount: TextBox 0.00 txtPaymentAmount Label Notes Button Submit btnSubmit Button Close btnClose
  4. Click the Employee Number text box and, in the Properties window, click the Events button
  5. Double-click the Leave field and implement the event as follows: 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; namespace WattsALoan5 { public partial class Payment : Form { public Payment() { InitializeComponent(); } private void txtEmployeeNumber_Leave(object sender, EventArgs e) { using (SqlConnection cnnWattsALoan = new SqlConnection("Data Source=(local);" + "Database='WattsALoan1';" + "Integrated Security=SSPI;")) { string strSelect = "SELECT FullName FROM Employees " + "WHERE EmployeeNumber = '" + txtEmployeeNumber.Text + "';"; SqlCommand cmdWattsALoan = new SqlCommand(strSelect, cnnWattsALoan); cnnWattsALoan.Open(); SqlDataReader rdrEmployees = cmdWattsALoan.ExecuteReader(); while (rdrEmployees.Read()) txtEmployeeName.Text = rdrEmployees[0].ToString(); } } } }
  6. Return to the form and double-click the Submit button
  7. Implement its even as follows: private void btnSubmit_Click(object sender, EventArgs e) { double PaymentAmount = 0.00; int LoanNumber = 1000; try { PaymentAmount = double.Parse(txtPaymentAmount.Text); } catch(FormatException) { MessageBox.Show("Invalid Payment Amount."); } try { LoanNumber = int.Parse(txtLoanNumber.Text); } catch (FormatException) { MessageBox.Show("Invalid Loan Number."); } // Don't save the record if there is no employee number if (txtEmployeeName.Text.Length == 0) { MessageBox.Show("You must enter a valid employee number."); return; } // Don't save the record if there is no loan number if( txtLoanNumber.Text.Length == 0) { MessageBox.Show("You must specify the loan number."); return; } // Make sure the user has specified the amount paid if( txtPaymentAmount.Text.Length == 0) { MessageBox.Show("You must specify the amount paid."); return; } using (SqlConnection cnnWattsALoan = new SqlConnection("Data Source=(local); " + "Database='WattsALoan1'; " + "Integrated Security='SSPI';")) { SqlCommand cmdWattsALoan = new SqlCommand("dbo.SpecifyCurrentBalance", cnnWattsALoan); cmdWattsALoan.CommandType = CommandType.StoredProcedure; SqlParameter prmWattsALoan = new SqlParameter(); prmWattsALoan.ParameterName = "@PmtDate"; prmWattsALoan.DbType = DbType.DateTime; prmWattsALoan.Value = dtpPaymentDate.Value.ToString("d"); cmdWattsALoan.Parameters.Add(prmWattsALoan); prmWattsALoan = new SqlParameter(); prmWattsALoan.ParameterName = "@EmplNbr"; prmWattsALoan.DbType = DbType.String; prmWattsALoan.Value = txtEmployeeNumber.Text; cmdWattsALoan.Parameters.Add(prmWattsALoan); prmWattsALoan = new SqlParameter(); prmWattsALoan.ParameterName = "@LoanNbr"; prmWattsALoan.DbType = DbType.Int32; prmWattsALoan.Value = LoanNumber.ToString(); cmdWattsALoan.Parameters.Add(prmWattsALoan); prmWattsALoan = new SqlParameter(); prmWattsALoan.ParameterName = "@PmtAmt"; prmWattsALoan.DbType = DbType.Double; prmWattsALoan.Value = PaymentAmount.ToString("F"); cmdWattsALoan.Parameters.Add(prmWattsALoan); prmWattsALoan = new SqlParameter(); prmWattsALoan.ParameterName = "@Comments"; prmWattsALoan.DbType = DbType.String; prmWattsALoan.Value = txtNotes.Text; cmdWattsALoan.Parameters.Add(prmWattsALoan); cnnWattsALoan.Open(); cmdWattsALoan.ExecuteNonQuery(); MessageBox.Show("A new payment has been made."); dtpPaymentDate.Value = DateTime.Today; txtEmployeeNumber.Text = ""; txtEmployeeName.Text = ""; txtLoanNumber.Text = ""; txtPaymentAmount.Text = "0.00"; txtNotes.Text = ""; } }
  8. Return to the form and double-click the Close button
  9. Implement its even as follows: private void btnClose_Click(object sender, EventArgs e) { Close(); }
  10. Access the Central form, add a button and change its properties as follows: (Name): btnNewPayment Text: New Payment...
  11. Double-click the Loan Allocations button and implement its event as follows: private void Central_Load(object sender, EventArgs e) { // CreateDatabase(); //CurrentBalanceCalculator(); } private void btnNewPayment_Click(object sender, EventArgs e) { NewPayment payment = new NewPayment(); payment.ShowDialog(); }
  12. To create a new form, on the main menu, click Project -> Add Windows Form...
  13. Set the Name to Payments and click Add
  14. From the Data Sources window, drag Payments and drop it on the form
  15. On the binding navigator, click the Add New Item button and press Delete
  16. Design the form as follows: Control Text Name Other Properties Button Close btnClose
  17. Double-click the Close button and implement its even as follows: private void btnClose_Click(object sender, EventArgs e) { Close(); }
  18. Access the Central form, add a button and change its properties as follows: (Name): btnPayments Text: View Payments...
  19. Double-click the Loan Allocations button and implement its event as follows: private void btnPayments_Click(object sender, EventArgs e) { Payments pmts = new Payments(); pmts.ShowDialog(); }
  20. Execute the application and open the New Payment form
  21. Create a few Payments and close the New Payment form
  22. Open the Payments form to see a summary of the payments
  23. Close the forms and return to your programming environment

Lesson Summary#

Exercises#

  1. Create a stored procedure named ProcessPayroll that takes 11 arguments: The number of hours worked for the first week (passed by value) The number of hours worked for the second week (passed by value) A number that represents the number of regular hours worked for the two weeks (passed by reference) A number for the salary paid for the regular hours of the two weeks (passed by reference) A number that represents the number of overtime hours worked for the two weeks (passed by reference) A number for the salary paid for the overtime hours of the two weeks (passed by reference) A number that represents the net salary paid for that payroll (passed by reference)

Home All rights reserved © 2008 C# Key