Created
June 28, 2012 12:06
-
-
Save i-e-b/3010963 to your computer and use it in GitHub Desktop.
A wrapper around System.Data.SqlClient to make it less weird.
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
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