|
xxx
ASP.net 2.0 C# Generics Execute Scalar Helper
by Ryan Olshan of StrongTypes.com
You code your application to pass any type of SqlDataReader and SqlConnection objects the helper function, eliminating the need for multiple helper functions for different database types.
This page demonstrates using Generics in C# to execute a Scalar function for any database provider using 1 helper function. Here is the code sample:
Web Form:
filename=/aspnet2/experiments/generics/cs_GenericsDbScalar.aspx
<%@ Page Language="C#" Debug="false" %>
<%@ Import Namespace="System" %>
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.OleDb" %>
<script runat="server">
protected void Page_Load(object sender, EventArgs e)
{
litRes.Text = dbTest();
}
private string dbTest()
{
string strCmdText = "Select Count(Color) From tblCars Where Color='Red';";
OleDbConnection conn = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=\Domains\learnasp.com\wwwroot\aspnet2\experiments\generics\TestDatabase.mdb;");
OleDbCommand cmd = new OleDbCommand(strCmdText);
return (DbHelper.ExecuteScalar<int>(conn, cmd) == 0 ? "Result returned 0" : "Result returned was not 0");
}
public class DbHelper
{
private static void msgError(string strException)
{
Page pageCurrent = new Page();
pageCurrent = (Page)HttpContext.Current.Handler;
pageCurrent.Controls.Add(new LiteralControl("Error: " + strException + "<br />"));
}
public static TScalar ExecuteScalar<TScalar>(IDbConnection paramConn, IDbCommand paramCmd)
{
TScalar val;
val = default(TScalar);
try
{
if (paramConn.GetType().Name.Replace("Connection", "") == paramCmd.GetType().Name.Replace("Command", ""))
{
paramCmd.Connection = paramConn;
paramConn.Open();
val = (TScalar)paramCmd.ExecuteScalar();
}
else
{
msgError("Connection and command object types do not match.");
}
}
catch(Exception ex)
{
msgError(ex.ToString());
}
finally
{
paramConn.Close();
}
return val;
}
}
</script>
<html>
<body>
<asp:Literal ID="litRes" runat="server" />
</body>
</html>
|