Created
August 20, 2019 08:31
-
-
Save amenayach/369827e1807b6b8d81b420797831dd64 to your computer and use it in GitHub Desktop.
Execute non-query MS SQL script using C#
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} | |
} |
Author
amenayach
commented
Aug 20, 2019
•
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment