Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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