Tuesday, September 27, 2011

Using SQL Data Reader in c#

Following example shows how to retrieve data in SQL as DateReader
public static string GetNames( int iHistUserID)
{
string sReturnValue = "";
SqlConnection objConn = new SqlConnection();
SqlCommand objCmd = new SqlCommand();
SqlDataReader dr = null;
string strConnectionString = "Connection string here";
try

{
objConn =
new SqlConnection(strConnectionString);
{

objCmd.Connection = objConn;
objCmd.CommandText =
"usp_SelUserInfo";
objCmd.CommandType = CommandType.StoredProcedure;
objCmd.Parameters.AddWithValue("@UserID", iUserID);
objConn.Open();

dr = objCmd.ExecuteReader();

}
if (dr.HasRows)
{
while ((dr.Read()))
{

sReturnValue = dr["Name"] == DBNull.Value ? clsConstants.GetStringIsNull : (string)dr["Name"];

}

}
catch (SqlException ex)
{
throw (new Exception("Sp Name here " + ex.ToString));
}
catch (Exception ex)
{
throw (ex);
}

finally

{
if ((objConn != null))
{
if ((objConn.State == ConnectionState.Open))
{

objConn.Close();

}

objConn.Dispose();

}
if ((dr != null))
{
if (!(dr.IsClosed))
{

dr.Close();

}

}
if ((objCmd != null))
{

objCmd.Dispose();

}

}
return sReturnValue;
}

No comments:

Post a Comment

Open default email app in .NET MAUI

Sample Code:  if (Email.Default.IsComposeSupported) {     string subject = "Hello!";     string body = "Excellent!";    ...