usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;usingSystem.Configuration;usingSystem.Data.SqlClient;namespace_04 Encapsulating SQL access method { Public classSqlHelper {//reading the connection string Private Static ReadOnly stringstr = configurationmanager.connectionstrings["Constr"]. ConnectionString;//the Name property in app. Config Constr /// <summary> ///This method can do additions and deletions to change/// </summary> /// <param name= "SQL" >SQL statements</param> /// <param name= "PS" >parameters in the SQL statement</param> /// <returns>The number of affected rows returned, int type</returns> Public Static intExecuteNonQuery (stringSqlparamssqlparameter[]ps) { //connecting to a database using(SqlConnection con=NewSqlConnection (str)) { using(SqlCommand cmd=NewSqlCommand (Sql,con)) {con. Open (); if(ps!=NULL) {cmd. Parameters.addrange (PS); } returncmd. ExecuteNonQuery (); } } } /// <summary> ///This method is used on the query/// </summary> /// <param name= "SQL" >SQL statements</param> /// <param name= "PS" >parameters in the SQL statement</param> /// <returns>Header column, object type</returns> Public Static ObjectExecutesclar (stringSqlparamssqlparameter[] PS) { using(SqlConnection con=NewSqlConnection (str)) { using(SqlCommand cmd=NewSqlCommand (Sql,con)) {con. Open (); if(ps!=NULL) {cmd. Parameters.addrange (PS); } returncmd. ExecuteScalar (); } } } /// <summary> ///This method is used to query the read data/// </summary> /// <param name= "SQL" >SQL statements</param> /// <param name= "PS" >parameters in the SQL statement</param> /// <returns>the SqlDataReader object is returned with the data</returns> Public StaticSqlDataReader ExecuteReader (stringSqlparamssqlparameter[] PS) {SqlConnection con=NewSqlConnection (str); using(SqlCommand cmd=NewSqlCommand (Sql,con)) { if(ps!=NULL) {cmd. Parameters.addrange (PS);//Add parameter ps to cmd } Try{con. Open (); returnCmd. ExecuteReader (System.Data.CommandBehavior.CloseConnection);//return data and close the connection } Catch(Exception ex) {con. Close (); Con. Dispose (); Throwex; } } } }}
Encapsulating SQL Access Methods