Dbhelper class for SQL statements
Code
// Data Connection
Public Static Readonly String Connectionstring = Configurationmanager. connectionstrings [ " Connectionstring " ]. Connectionstring;
// Perform add, delete, modify, and delete operations
Public Static Int Excutenonquery ( String SQL)
{
Using (Sqlconnection Conn = New Sqlconnection (connectionstring ))
{
Sqlcommand Comand = New Sqlcommand (SQL, Conn );
If (Conn. State ! = Connectionstate. open)
Conn. open ();
Int Val = Comand. executenonquery ();
Return Val;
}
}
// Perform query operations
Public Static Sqldatareader excutereader ( String SQL)
{
Sqlconnection Conn = New Sqlconnection (connectionstring );
If (Conn. State ! = Connectionstate. open)
Conn. open ();
Sqlcommand Comand = New Sqlcommand (SQL, Conn );
Return Comand. executereader ();
}
Dbhelper class that can be passed in SQL statements or stored procedures
Code
/// <Summary>
/// Connection string
/// </Summary>
Public Static Readonly String Connectionstring = Configurationmanager. connectionstrings [ " Connectionstring " ]. Connectionstring;
/// <Summary>
/// Execute SQL commands
/// (For adding, modifying, and deleting operations)
/// </Summary>
/// <Param name = "connectionstring"> Connection string </Param>
/// <Param name = "command"> SQL command object </Param>
/// <Returns> Returns the number of affected rows. </Returns>
Public Static Int Executenonquery ( String Connectionstring, sqlcommand command)
{
Try
{
Using (Sqlconnection Conn = New Sqlconnection (connectionstring ))
{
Command. Connection = Conn;
If (Conn. State ! = Connectionstate. open)
Conn. open ();
Int Val = Command. executenonquery ();
Return Val;
}
}
Catch (Exception ex)
{
Throw New Applicationexception ( " Executenonquery error! " , Ex );
}
}
/// <Summary>
/// Run the SQL command to return the reader object.
/// (For query operations)
/// Note: You must disable the reader object after it is used. Otherwise, the connection used by the reader object will not be automatically closed!
/// </Summary>
/// <Param name = "connectionstring"> Connection string </Param>
/// <Param name = "command"> Command object </Param>
/// <Returns> Returns the queried reader object. </Returns>
Public Static Sqldatareader executereader ( String Connectionstring, sqlcommand command)
{
Sqlconnection Conn = New Sqlconnection (connectionstring );
Try
{
Command. Connection = Conn;
If (Conn. State ! = Connectionstate. open)
Conn. open ();
Sqldatareader RDR = Command. executereader (commandbehavior. closeconnection );
Return RDR;
}
Catch (Exception ex)
{
Conn. Close ();
Throw New Applicationexception ( " Executereader error! " , Ex );
}
}