SIGN UP MEMBER LOGIN:    
ARTICLE

Configuring Parameters and Parameter Data Types-ADO.NET

Posted by Puran Mehra Articles | ADO.NET in C# August 12, 2009
In this article I will explain you about command object, benefits of parameterized command, DbParameter Object, ParameterDirection Property and Parameter Data Types in ADO.NET
Reader Level:
Download Files:
 

Configuring Parameters and Parameter Data Types (ADO.NET)

 

Command objects use parameters to pass values to SQL statements or stored procedures, which facilitates type checking and validation.

 

Command text, parameter input is treated as a constant (literal value) not as executable code.

 

Command text as constant guard against "SQL injection" attacks, in which an attacker inserts a command that compromises security on the server into an SQL statement.

 

See the below code to understand about parameterized query its other important related topics.

 

Begin your application by launching VS.NET and creating a new project using File - > Project and choose C# Windows Application template as shown in figure below:


add_Record_project.gif
               

Add a new item application configuration file as shown below from Project -> Add New Item


acf.gif
 

The code for the application configuration file:

 

<?xml version="1.0" encoding="utf-8" ?>

<configuration>

  <connectionStrings>

    <add name="constr" connectionString="initial catalog=puran; data source=MCN002; integrated security=sspi"/>

   </connectionStrings>

</configuration>

                  

Note: In the above code I have made a connection using windows authentication.

 

In the form design and button, textboxes and labels as follow:


add_form.gif
 

Add the necessary reference file from the solution explorer, Reference as below:


add_reference.gif
 

Code for adding records in a database through textbox using parameterized query in disconnected model.

 

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Linq;

using System.Text;

using System.Data.SqlClient;

using System.Data.Common;

using System.Configuration;

 

using System.Windows.Forms;

 

namespace adding_Records_disconnected

{

    public partial class Form1 : Form

    {

        public Form1()

        {

            InitializeComponent();

        }

 

        SqlConnection con;

        SqlCommand cmd;

 

        private void button1_Click(object sender, EventArgs e)

        {

            con = new SqlConnection(ConfigurationManager.ConnectionStrings["constr"].ConnectionString);

            cmd = new SqlCommand();

            cmd.Connection = con;

 

            cmd.Parameters.Add(new SqlParameter("@RollNo", SqlDbType.Int));

            cmd.Parameters["@RollNo"].Value = textBox1.Text;

 

            cmd.Parameters.Add(new SqlParameter("@Name", SqlDbType.VarChar));

            cmd.Parameters["@Name"].Value = textBox2.Text;

 

            cmd.Parameters.Add(new SqlParameter("@Fees", SqlDbType.Float));

            cmd.Parameters["@Fees"].Value = textBox3.Text;

 

            cmd.CommandText="insert into student values(@RollNo, @Name, @Fees)";

 

            con.Open();

            cmd.ExecuteNonQuery();

 

            con.Close();

            MessageBox.Show("Record inserted");

        }

    }

}

 

The above code explanation will be clearer with the theoretical aspect below. Read the following paragraphs for better understanding of the code listed in the article.

 

DbParameter Object

 

A DbParameter object can be created by using its constructor, or by adding it to the DbParameterCollection by calling the Add method of the DbParameterCollection collection.

 

The Add method will take as input either constructor arguments or an existing parameter object, depending on the data provider.

 

ParameterDirection Property

 

When adding parameters, you must supply a ParameterDirection property for parameters.

 

The following table shows the ParameterDirection values that you can use with the ParameterDirection enumeration.

 

Member Name

Description

Input

The parameter is an input parameter. This is the default.

Output

The parameter is an output parameter.

Input/Output

The parameter can perform both input and output.

Return Value

The parameter represents a return value from an operation such as a stored procedure, built-in function, or user-defined function.

 

Note: SQL Server has only two-parameter direction Input and Output.

 

Parameter Data Types

 

In the above code I have used SqlDbType of the Parameter object. 

 

The data type of a parameter is specific to the .NET Framework data provider. Specifying the type converts the value of the Parameter to the .NET Framework data provider type before passing the value to the data source.

 

Begin your application by launching VS.NET and creating a new project using File - > Project and choose C# Windows Application template as shown in figure below:


 

show_record_project.gif

Add a new item application configuration file as shown below from Project -> Add New Item


acf.gif
 

The code for the application configuration file:

 

<?xml version="1.0" encoding="utf-8" ?>

<configuration>

  <connectionStrings>

    <add name="constr" connectionString="initial catalog=puran; data source=MCN002; integrated security=sspi"/>

   </connectionStrings>

</configuration>

                  

Note: In the above code I have made a connection using windows authentication.

 

Design the form as below:


show_form.gif
 

Add the necessary reference file from the solution explorer, Reference as below:


add_reference.gif
 

Code for displaying records in a database through textbox using parameterized query in disconnected model.

 

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.Configuration;

using System.Data.Common;

using System.Data.SqlClient;

 

namespace shwing_records_disconnected

{

    public partial class Form1 : Form

    {

        public Form1()

        {

            InitializeComponent();

        }

 

        SqlConnection con;

        SqlCommand cmd;

 

        private void button1_Click(object sender, EventArgs e)

        {

            con = new SqlConnection(ConfigurationManager.ConnectionStrings["constr"].ConnectionString);

            cmd = new SqlCommand();

            cmd.Connection = con;

 

            cmd.Parameters.Add(new SqlParameter("@RollNo", SqlDbType.Int));

            cmd.Parameters["@RollNo"].Value = textBox4.Text;

 

            cmd.Parameters.Add(new SqlParameter("@Name", SqlDbType.VarChar,50));

            cmd.Parameters["@Name"].Direction = ParameterDirection.Output;

 

            cmd.Parameters.Add(new SqlParameter("@Fees", SqlDbType.Float));

            cmd.Parameters["@Fees"].Direction = ParameterDirection.Output;

 

            cmd.CommandText = "select @Name=Name, @Fees=Fees from student where RollNo=@RollNo";

 

            con.Open();

            cmd.ExecuteNonQuery();

 

            textBox1.Text = cmd.Parameters["@RollNo"].Value.ToString();

            textBox2.Text = cmd.Parameters["@Name"].Value.ToString();

            textBox3.Text = cmd.Parameters["@Fees"].Value.ToString();

            con.Close();

            MessageBox.Show("Record Displayed");

        }

    }

}

 

Advantages of parameterized commands: 

  • Parameterized commands can also improve query execution performance, because they help the database server accurately match the incoming command with a proper-cached query plan.
  • Parameterized command provide security and performance benefits.
  • Parameterized commands provide a convenient method for organizing values passed to a data source.

Note: I have attached code of the above program. You have to create table and change the necessary database connection string in configuration file.

 

Conclusion

 

After reading this article you might be clear about command object, benefits of parameterized command, DbParameter Object, ParameterDirection Property and Parameter Data Types in ADO.NET using SQL Server as database.

 

Your feedback and constructive contributions are welcome.  Please feel free to contact me for feedback or comments you may have about this article.

Login to add your contents and source code to this article
share this article :
post comment
 

Yes! Thats why i have said It will improve the security.

But my question is when you release this query from your application to the sql server then how it will use the sql cached plans???

Thats my doubt.

Thanks!!!

senthilkumar

Posted by Senthilkumar Aug 12, 2009

There is big different in passing simplly passing values in text box rather than as parameters. Pratmertirized query help in prention of SQL Injection Attacks. Read my previous article on SQL Injection Attacks which will clear your doubt.

Thanks,
Puran

Posted by Puran Mehra Aug 12, 2009

Thanks,

We will explaining in context of stored procedure in my coming articles.

Posted by Puran Mehra Aug 12, 2009

Really it was informative.
But i have one doubt. You have mentioned like it will use the query cached plan. Here the query formation may be different. But when you release the query from your application then it will be same as normal query.

Example
insert into student values(@RollNo,@Name,@Fees)
this normally programmers used like
insert into student values(textBox1.Text, textBox2.Text, textBox3.Text)

Finally both will be same at the point of release from the application.
How it can use the cached plans like stored procedures??????

I agree it will improve the security.

Thank you...

Erode Senthilkumar

Posted by Senthilkumar Aug 12, 2009
Team Foundation Server Hosting
Become a Sponsor
PREMIUM SPONSORS
  • Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
    The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
Nevron Gauge for SharePoint
Become a Sponsor