Skip to content

Instantly share code, notes, and snippets.

@trailmax
Forked from i-e-b/SqlHelper.cs
Created September 19, 2019 11:50
Show Gist options
  • Save trailmax/012d483a8e4aab63cb0a490585e15d88 to your computer and use it in GitHub Desktop.
Save trailmax/012d483a8e4aab63cb0a490585e15d88 to your computer and use it in GitHub Desktop.
A wrapper around System.Data.SqlClient to make it less weird.
using System;
namespace System.Data.SqlClient {
public class SqlHelper {
readonly string connectionString;
public SqlHelper(string connectionString) { this.connectionString = connectionString; }
public string StringCommand (string commandString, Action<SqlParameterCollection> bindingCommand) {
using (var connection = new SqlConnection(connectionString)) {
connection.Open();
using (var command = connection.CreateCommand()) {
bindingCommand(command.Parameters);
command.CommandText = commandString;
return command.ExecuteScalar().ToString();
}
}
}
public int CountCommand (string commandString, Action<SqlParameterCollection> bindingCommand) {
using (var connection = new SqlConnection(connectionString)) {
connection.Open();
using (var command = connection.CreateCommand()) {
bindingCommand(command.Parameters);
command.CommandText = commandString;
return (int)command.ExecuteScalar();
}
}
}
public void ExecuteCommand (string commandString, Action<SqlParameterCollection> bindingCommand) {
using (var connection = new SqlConnection(connectionString)) {
connection.Open();
using (var command = connection.CreateCommand()) {
bindingCommand(command.Parameters);
command.CommandText = commandString;
command.ExecuteNonQuery();
}
}
}
public void ExecuteReader (string commandString, Action<SqlParameterCollection> bindingCommand, Action<SqlDataReader> readingAction) {
using (var connection = new SqlConnection(connectionString)) {
connection.Open();
using (var command = connection.CreateCommand()) {
bindingCommand(command.Parameters);
command.CommandText = commandString;
using (var rdr = command.ExecuteReader()) {
while (rdr.Read()) readingAction(rdr);
}
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment