Friday, 6 December 2013

READING AND WRITING DATA-----(DbParameters Object)

In First section of Reading and Writing Data,We have seen how and why do we use DbCommand Object.Here we will know about DbParameters Object..


Stored procedures typically require parameter values to be passed to them to execute. For example, a stored procedure called CustOrderHist might require a customer identification to retrieve information about the appropriate customer. You can create System.Data.Common.DbParameter objects by using the Parameters.Add method on the Command object, as shown here.



C# Code:


var nw = ConfigurationManager.ConnectionStrings["nw"];
var connection = new SqlConnection();
connection.ConnectionString = nw.ConnectionString;
var cmd = connection.CreateCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "CustOrderHist";
DbParameter parm = cmd.CreateParameter();
parm.ParameterName = "@Id";
parm.Value = "ANATR";
cmd.Parameters.Add(parm);


This code creates a DbConnection object and a DbCommand object. It also configures the DbCommand object to execute a stored procedure called uspGetCustomerById, whichrequires a single parameter called @Id that is assigned the value “ANATR.”

We can use the name assigned to the DbParameter object to access the parameter through code. For example, to retrieve the value currently in the @Id SQL parameter, use the following code:

C# Code
var id = (string)cmd.Parameters["@Id"].Value;

No comments:

Post a Comment