Function: reflects the method for dynamically calling SQL Command based on the called method name.
Copy codeThe Code is as follows: // <summary>
/// Attributes of the stored procedure
/// Name of the ProcName Stored Procedure
/// MethodName name of the SqlCommand method executed
/// PrmList stored procedure parameters
/// </Summary>
Public class ExeProc
{
Public string ProcName;
Public string MethodName;
Public object [] PrmValue;
}
Based on the name of the stored procedure
And parameters to execute the specified stored procedure and call the sqlCommand Method
Copy codeThe Code is as follows: public class DataHelper
{
Private string connString = null;
Public DataHelper (string conStr)
{
This. connString = conStr;
}
/// <Summary>
/// Execute the Stored Procedure
/// </Summary>
/// <Param name = "ep"> attributes of the stored procedure
/// Name of the ProcName Stored Procedure
/// MethodName name of the SqlCommand method executed
/// PrmList stored procedure parameters
/// </Param>
/// <Returns> return the execution result </returns>
Public object ExecProcRetObj (ExeProc ep)
{
If (this. connString! = Null & this. connString! = String. Empty)
{
Try
{
SqlConnection con = new SqlConnection (this. connString );
SqlCommand cmd = new SqlCommand ();
Cmd. Connection = con;
Cmd. CommandText = "Exec" + ep. ProcName + "";
Foreach (object obj in ep. PrmValue)
{
Cmd. CommandText + = obj + ",";
}
Cmd. CommandText = cmd. CommandText. Remove (cmd. CommandText. Length-1, 1 );
Type ty = cmd. GetType ();
Con. Open ();
// Use reflection to execute the corresponding method based on the input method name
Object retObj = ty. InvokeMember (ep. MethodName, BindingFlags. InvokeMethod, null, cmd, null );
If (retObj. GetType (). FullName = "System. Data. SqlClient. SqlDataReader ")
{
// Convert the returned object to a DataTable object
DataTable retDt = new DataTable ();
RetDt. Load (retObj as SqlDataReader );
Con. Close ();
Con. Dispose ();
Return retDt;
}
Return retObj;
}
Catch (Exception ex)
{
System. Windows. Forms. MessageBox. Show ("An error occurred while obtaining data \ n" + ex. Message );
}
}
Return null;
}
}