Skip to content

Instantly share code, notes, and snippets.

@amenayach
Created August 20, 2019 08:31
Show Gist options
  • Save amenayach/369827e1807b6b8d81b420797831dd64 to your computer and use it in GitHub Desktop.
Save amenayach/369827e1807b6b8d81b420797831dd64 to your computer and use it in GitHub Desktop.
Execute non-query MS SQL script using C#
namespace SqlSample
{
using System;
using System.Data;
using System.Data.SqlClient;
public class SqlService
{
private readonly string connectionString;
public SqlService(string connectionString)
{
this.connectionString = connectionString;
}
public bool ExecuteNonQuery(string query, params SqlParameter[] parameters)
{
var result = false;
try
{
using (var connection = new SqlConnection(connectionString))
using (var command = new SqlCommand(query, connection))
{
if (parameters.Length > 0)
{
command.Parameters.AddRange(parameters);
}
if (command.Connection.State != ConnectionState.Open)
{
command.Connection.Open();
}
command.ExecuteNonQuery();
}
}
catch (Exception ex)
{
//Logging exception
throw;
}
return result;
}
}
}
@amenayach
Copy link
Author

amenayach commented Aug 20, 2019

//Usage sample
var sqlService = new SqlService("PUT_YOUR_CONNECTION_STRING_HERE");
var success = sqlService.ExecuteNonQuery(
    "UPDATE SOMETABLE SET [NAME] = @name, [MODIFIED] = @modified",
    new SqlParameter("@name", "Bassam"),
    new SqlParameter("@modified", DateTime.UtcNow));

if(success) {
    //Do something
}
else 
{
    //Do something else
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment