Skip to content

Instantly share code, notes, and snippets.

@NMZivkovic
Created September 28, 2017 11:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save NMZivkovic/4c1f9c1d11abce3a0915ae51e46287dc to your computer and use it in GitHub Desktop.
Save NMZivkovic/4c1f9c1d11abce3a0915ae51e46287dc to your computer and use it in GitHub Desktop.
public class SqlDataHandler : IDisposable
{
private string _connectionString;
private SqlConnection _sqlConnection;
public SqlDataHandler()
{
_connectionString = ConfigurationManager.AppSettings["connectionString"];
_sqlConnection = new SqlConnection(_connectionString);
_sqlConnection.Open();
}
public Entity ReadEntity()
{
var entity = new Entity();
try
{
using (var readCommand = new SqlCommand("select * from Entity", _sqlConnection))
{
var reader = readCommand.ExecuteReader();
while (reader.Read())
{
entity.CurrentValue = reader.GetInt32(0);
entity.Type = (EntityType)reader.GetInt32(1);
}
reader.Close();
}
}
catch(Exception e)
{
Console.WriteLine("Failed to read the data!");
}
return entity;
}
public void UpdateDataFieldInEntity(Entity entity, int newValue)
{
var toValue = entity.GetNewValueBasedOnType(newValue);
try
{
using (var updateCommand = new SqlCommand(String.Format("update Entity set Data = {0} where Data = {1}", toValue, entity.CurrentValue), _sqlConnection))
{
updateCommand.ExecuteNonQuery();
}
}
catch (Exception e)
{
Console.WriteLine("Failed to modify data");
}
}
public void Dispose()
{
_sqlConnection.Close();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment