Few months ago I posted my code Getting a single value from the DB. I implemented suggested changes and this is how it looks like right now:
public class DataBase : Page
{
protected static readonly ILog log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
protected static string ConnectionString;
public DataBase()
{
ConnectionString = GetConnectionString();
}
public static String GetConnectionString()
{
return ConfigurationManager.ConnectionStrings["abc"].ConnectionString;
}
public static T GetValue<T>(string query)
where T : IComparable, IConvertible, IEquatable<T>
{
Object value = GetValue(query);
if (Convert.IsDBNull(value))
return GetDefaultValue<T>();
return (T)Convert.ChangeType(value, typeof(T));
}
public static T GetDefaultValue<T>()
where T : IComparable, IConvertible, IEquatable<T>
{
if (typeof(T) == typeof(String))
return (T)(object)String.Empty;
return default(T);
}
private static Object GetValue(string query)
{
try
{
using (SqlConnection connection = new SqlConnection(ConnectionString))
using (SqlCommand command = new SqlCommand(query, connection))
{
connection.Open();
return command.ExecuteScalar();
}
}
catch (Exception e)
{
LogQueryError(query, e);
return DBNull.Value;
}
}
protected static void LogQueryError(string query, Exception e)
{
log.Error(string.Format("Error while executing Query ({0}): {1}", query, e.Message));
}
}
One explanation. The purpose of where T : IComparable, IConvertible, IEquatable<T>
is to have single method for value types and strings. (inspired by C# Generic constraints to include value types AND strings
What do you think about this piece of code?
DataBase.GetValue<int>("select someNumber from dbo.parts where partName = '" + someVariable + "'");
– RobH Jul 6 at 10:23SqlCommand
object instead? – EBrown Jul 6 at 15:06string
. – EBrown Jul 6 at 16:27