Created
September 28, 2017 11:08
-
-
Save NMZivkovic/4c1f9c1d11abce3a0915ae51e46287dc to your computer and use it in GitHub Desktop.
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
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