Tuesday, March 18, 2008

Get data from the database stright away! .NET

Sometimes you want the most strightforward way to get data from the database without going through the N-tiers stuffs.

This technique have advantages and disadvantages,

Advantage:
The fastest data access beside store procedures.
Simple and strighforward.


Disadvantage:
Not strongly typed,
Possible of memory leak if not code propertly
Things get complicated if involve insert record or large table which have many columns.

public string ReadCustomerFromDB()
{

string sql = "Select
name, phone, age from Customers where customerid =
@customerId";

string output = "";

using (SqlConnection myConnection = new
SqlConnection(ConfigurationManager.ConnectionStrings["Northwind"].ConnectionString))
{
myConnection.Open();

SqlCommand mySqlCommand = new SqlCommand(sql,
myConnection);

mySqlCommand.Parameters.AddWithValue("@customerId", 123456);

SqlDataReader datareader =
mySqlCommand.ExecuteReader();

while
(datareader.Read())
{

Output +=
datareader["name"];

Output +=
datareader["age"];
}

datareader.Close();
}
return output;
}

No comments: