In this post we are exploring more about Parameters Queries.
For Example if the user want to view information for one specific employee.To get this information from
our Employees table, we need to run the following query, replacing EmployeeID with the ID of the employee
in which the user was interested:
For example:
SELECT EmployeeID, Name, Username, Password
FROM Employees WHERE EmployeeID = EmployeeID
For This, we have added a Textbox control into which users can enter
the ID of the employee whose information they want to see.
Now, we could perform this query using the following code:
If the user entered the number into the text box and clicked the button,
the following query would be run:
SELECT EmplyeeID, Name, Username, Password
FROM Employees WHERE EmployeeID = 5
The database would run this query without complaint, and our program would
execute as expected. However, if as is perhaps more likely—the user entered an
employee’s name, our application would attempt to run the following query:
For example:
SELECT EmployeeID, Name, Username, Password
FROM Employees
WHERE EmployeeID = abc
This query would cause an error in the database, which would, in turn, cause an
exception in our web form. As a safeguard against this eventuality, ADO.NET allows
we to define parameters in our query, and give each of those parameters a type.
Inserting parameters into our query is a reasonably simple task:
In the following example, a new OracleCommand object named myOracleCommand
is set to the OracleCommand object returned by calling the CreateCommand() method
of myOracleConnection:
String query = "select empno,deptno,name,address from emp WHERE empno=:EmployeeID";
objCmd.Parameters.Add(":EmployeeID", System.Data.SqlDbType.Int);
objCmd.Parameters[":EmployeeID"].Value = employeeID;
We have added a
placeholder to the query for our
parameter; it comprises the :
symbol,
followed by an identifier for the parameter (in this case, we have used EmployeeID).
Next, we need to add this parameter to the
OracleCommand object, and give it a value:
objCmd.Parameters.Add(":EmployeeID", System.Data.SqlDbType.Int);
objCmd.Parameters[":EmployeeID"].Value = employeeID;
Here, we call the Add method of comm.Parameters, passing in the name of the
parameter (EmployeeID) and the parameter’s type; we have told ADO.NET that we are
expecting an int to be passed to the database, but we could specify any of the SQL
Server data types here.
No comments:
Post a Comment
Please do not enter any spam link in the comment box.