Directly connecting to a database is generally not recommended when integrating with other systems. However, if you absolutely must connect straight to a database and run queries against it, here’s how you can do it. (We needed to connect to a Access DB – code may vary with change of DB)
Have the DB connection link – of course you should use custom parameters for any sensitive information like username or password.
ConnectionsString = "Server=00.00.0.00,0000; Initial Catalog=DBNAME; User=username; Password=Password";
Initiate the connection to the database:
var connection = new System.Data.SqlClient.SqlConnection();
connection.ConnectionString = DBConnectionString;
var cmd = new System.Data.SqlClient.SqlCommand();
connection.Open();
Declare the call and its parameters:
var cmdCallProcedure = new System.Data.SqlClient.SqlCommand("spProcedureName", connection);
cmdCallProcedure.CommandType = System.Data.CommandType = System.Data.CommandType.StoredProcedure;
//Input parameters
cmdCallProcedure.Parameters.AddWithValue("@ParameterName", "Value to Pass");
//Output parameters
var outputParams = new System.Data.SqlClient.SqlParameter("@ParameterName1", System.Data.SqlDbType.Int);
outputParams = new System.Data.SqlClient.SqlParameter("@ParameterName2", System.Data.SqlDbType.Int);
outputParams.Direction = System.Data.ParameterDirection.Output;
cmdCallProcedure.Parameters.Add(outputParams);
Define and execute the call
//execute the call
cmdCallProcedure.ExecuteNonQuery();
//read the outputted values
var OutputParam1 = cmdCallProcedure.Parameters["@ParameterName1"].Value;
Close the connection:
connection.Close();

Leave a Reply