Saturday, 15 August 2009

SQLHelper - Microsoft Data Access Application Block

When starting to program in c# .net, it helps to use a class provided by Microsoft which allows you to code more quickly and effectively. Instead of creating several lines of code to perform a database task you can simply just use a couple of lines.

This is a really basic example of how the class can be used.

Add this namespace to your page

using Microsoft.ApplicationBlocks.Data;

// Setup Connection
SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["TestConnection"].ConnectionString);


protected void Page_Load(object sender, EventArgs e)
{

// Open datareader to read through our items
SqlDataReader dr = SqlHelper.ExecuteReader(cn, CommandType.Text, "SELECT * FROM tbl_blogs ORDER BY title");

// See if we have any data and if so then cycle through the datareader
while (dr.Read())
{
Response.Write(Convert.ToString(dr["title"]) + ""<br />");
}

// Close the datareader or we cant use the connection for other operations
dr.Close();

}

}


There is more information available on http://msdn.microsoft.com/en-us/library/ms954827.aspx

No comments: