SqlHelper tool class,
Public class SqlHlper
{
Public static readonly string constr = ConfigurationManager. ConnectionStrings ["constr"]. ConnectionString;
// Execute add, delete, and modify operations
Public static object ExecuteNonQuery (string SQL, params SqlParameter [] pms) // SqlParameter must call Data. SqlClient
{
Using (SqlConnection con = new SqlConnection (constr ))
{
Using (SqlCommand cmd = new SqlCommand (SQL, con ))
{
If (pms! = Null)
{
Cmd. Parameters. AddRange (pms );
}
Con. Open ();
Return cmd. ExecuteNonQuery ();
}
}
}
// Obtain a single data
Public static object ExecteScalar (string SQL, params SqlParameter [] pms)
{
Object obj = null;
Using (SqlConnection conn = new SqlConnection (constr ))
{
SqlCommand cmd = new SqlCommand (SQL, conn );
Conn. Open ();
If (pms! = Null)
{
Cmd. Parameters. AddRange (pms );
}
Obj = cmd. ExecuteScalar ();
}
Return obj;
}
// Obtain multiple data
Public static SqlDataReader GetDataReader (string SQL, params SqlParameter [] sps)
{
SqlConnection conn = new SqlConnection (constr );
Using (SqlCommand cmd = new SqlCommand (SQL, conn ))
{
If (sps! = Null)
{
Cmd. Parameters. AddRange (sps );
}
Conn. Open ();
Return cmd. ExecuteReader (CommandBehavior. CloseConnection );
}
}
// Query multiple data entries
Public static DataTable GetDataTable (string SQL, params SqlParameter [] sps)
{
DataTable dt = new DataTable ();
Using (SqlDataAdapter da = new SqlDataAdapter (SQL, constr ))
{
If (sps! = Null)
{
Da. SelectCommand. Parameters. AddRange (sps );
}
Da. Fill (dt );
}
Return dt;
}
}