How to tips and tricks for Microsoft Visual Studio .net

Tuesday, June 23, 2009

Simplifying the ExecuteNonQuery Method

Tagging onto the last post, I have another two functions that make my life easier...

You still need to pick up a connection string from your Web.Config for both of these functions:


Public static string GetConnectionString()

{

return System.Configuration.ConfigurationManager.AppSettings["sqlConnectionString"];

}


Simplifying the ExecuteNonQuery Method:


public static String ExecuteNonQuery(String lvCommand)

{

// This will execute a SQL Command (Update or Insert Into) and will return the number of records String lvReturn = "0";

// Setup your connection to your database

SqlConnection cn = new SqlConnection(GetConnectionString());

// Create a SQLCommand object

SqlCommand lvSQL = new SqlCommand(lvCommand, cn);

try

{

// Open a connection to your database

cn.Open();

// Execute your query

lvReturn = lvSQL.ExecuteNonQuery().ToString();

}

catch (Exception ex)

{

// If there is an error set lvReturn to "0"

lvReturn = "0";

}

finally

{

// Whatever happens, check to see if the connection is still open and if it is, close it

if (cn.State != ConnectionState.Closed)

{

cn.Close();

}

}

// Return the number of records affected

return lvReturn;

}


To use the function, call it like this...


String lvCommand = "Update A_Table Set A_Field = 'The String' Where AnotherField = 'Another String'";

Int32 lvAffectedRowCount = Int32.Parse(ExecuteScalar(lvCommand));


Again, Pretty simple.

No comments:

Post a Comment