Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Basics Of Stored Procedures In .NET

DZone's Guide to

Basics Of Stored Procedures In .NET

· Database Zone ·
Free Resource

Compliant Database DevOps and the role of DevSecOps DevOps is becoming the new normal in application development, and DevSecOps is now entering the picture. By balancing the desire to release code faster with the need for the same code to be secure, it addresses increasing demands for data privacy. But what about the database? How can databases be included in both DevOps and DevSecOps? What additional measures should be considered to achieve truly compliant database DevOps? This whitepaper provides a valuable insight. Get the whitepaper

Using 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.

Compliant Database DevOps and the role of DevSecOps DevOps is becoming the new normal in application development, and DevSecOps is now entering the picture. By balancing the desire to release code faster with the need for the same code to be secure, it addresses increasing demands for data privacy. But what about the database? How can databases be included in both DevOps and DevSecOps? What additional measures should be considered to achieve truly compliant database DevOps? This whitepaper provides a valuable insight. Get the whitepaper

Topics:

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}