Basics Of Stored Procedures In .NET
Join the DZone community and get the full member experience.
Join For FreeUsing stored procedures instead of writing SQL queries manually is a good thing to do in pretty much every application that involves SQL databases.
In C#, to execute a stored procedure, a developer needs to initialize an instance of SqlConnection, set the connection string, create an instance of SqlCommand, add the parameters, set the type of the command to StoredProcedure and use ExecuteNonQuery() to execute it. Using this every single time for every other stored procedure that needs to be called can involve more code that a developer probably wants to see in a function.
Therefore, I was working on a function that would unify all this code in one place, and whenever needed, it can be called in one line of code.
Suppose I have a database on my SQL Server called MySystem. There is also a table, called Users. Now, I also a have a stored procedure to simplify the process of adding new users to the system:
PROCEDURE [dbo].[AddUser] (@userID CHAR(36), @username CHAR(25), @password CHAR(25), @fullname CHAR(60), @role INT) AS INSERT INTO Users VALUES (@userID, @username, @password, @role, @fullname)
Don’t get confused by such a long userID – a GUID is used as a user identifier in my case.
Here is my function that will execute stored procedures in C#:
enum ProcedureType { UpdateOnly, WithReturn } SqlDataReader ExecuteProcedure(string connectionString, string procedureName, Dictionary<string,string> parameters,ProcedureType pType) { SqlDataReader reader = null; SqlConnection sqlConn; SqlCommand sqlCmd; try { sqlConn = new SqlConnection(connectionString); sqlCmd = new SqlCommand(procedureName, sqlConn); sqlCmd.CommandType = CommandType.StoredProcedure; if (parameters != null) { foreach (string parameter in parameters.Keys) { sqlCmd.Parameters.AddWithValue(parameter, parameters[parameter]); } } if (pType == ProcedureType.UpdateOnly) { sqlConn.Open(); sqlCmd.ExecuteNonQuery(); sqlConn.Close(); } else { sqlConn.Open(); reader = sqlCmd.ExecuteReader(); } } catch (Exception ex) { System.Diagnostics.Debug.Print( string.Format("An exception occured when executing the {0} stored procedure. {1}", procedureName, ex.Message)); } return reader; }
Its parameters are pretty much self explanatory – it gets the connection string, the name of the stored procedure, the list of parameters to be passed to the procedure and the type of the procedure. UpdateOnly means that the stored procedure is executed and there is no value that needs to be read by the end user. WithReturn means that there are results returned (in case with SELECT statements, for example). If a value is not returned, SqlDataReader is null. Otherwise, it contains the response data. Mention the fact that the list of parameters is represented as Dictionary<string,string>. This is because parameters to the procedure are passed as value pairs – the parameter name and the value of the parameter.
Here is a piece of sample code that shows how to use the above mentioned function applied to my sample database (should be places in an event handler to be triggered):
string connectStr = @"server=DEN-PC\SQLEXPRESS;database=MySystem;uid=admin;pwd=pass"; Dictionary<string, string> parameters = new Dictionary<string, string>(); parameters.Add("@userID", "4d36e978-e325-11ce-bfc1-08002be10311"); parameters.Add("@username", "somename"); parameters.Add("@password", "passHash"); parameters.Add("@role", "1"); parameters.Add("@fullname", "Someone Pass"); SqlDataReader reader = ExecuteProcedure(connectStr, "AddUser", parameters, ProcedureType.WithReturn);
Pretty simple, and can be easily reused when needed.
NOTE: You need to declare the System.Data and System.Data.SqlClient namespaces before using the function.
Opinions expressed by DZone contributors are their own.
Trending
-
Comparing Cloud Hosting vs. Self Hosting
-
Five Java Books Beginners and Professionals Should Read
-
Alpha Testing Tutorial: A Comprehensive Guide With Best Practices
-
Implementing a Serverless DevOps Pipeline With AWS Lambda and CodePipeline
Comments