public static Class SqlHelper
{
Get connection string
private static readonly String constr = configurationmanager.connectionstrings["ConnectionStr"]. ConnectionString;
ExecuteNonQuery () method
ExecuteScalar () method
ExecuteReader () method
Executedatatable () method
Perform additions, deletions, and modifications
public static int ExecuteNonQuery (String sql, params sqlparameter[] PMS)
{
Use the Using keyword to define a scope that automatically calls the Dispose object of this class instance at the end of the range
using (SqlConnection con = new SqlConnection (CONSTR))
{
To create an Execute SQL command object
using (SqlCommand cmd = new SqlCommand (sql, con))
{
Determine if the SQL parameter was passed
if (PMS! = null)
{
To add a parameter to the Parameters collection
Cmd. Parameters.addrange (PMS);
}
Con. Open ();
return CMD. ExecuteNonQuery ();
}
}
}
Execution that returns a single value.
public static Object ExecuteScalar (String sql, params sqlparameter[] PMS)
{
using (SqlConnection con = new SqlConnection (CONSTR))
{
using (SqlCommand cmd = new SqlCommand (sql, con))
{
if (PMS! = null)
{
Cmd. Parameters.addrange (PMS);
}
Con. Open ();
return CMD. ExecuteScalar ();
}
}
}
Perform a return SqlDataReader
public static SqlDataReader ExecuteReader (String sql, params sqlparameter[] PMS)
{
SqlConnection con = new SqlConnection (CONSTR);
using (SqlCommand cmd = new SqlCommand (sql, con))
{
if (PMS! = null)
{
Cmd. Parameters.addrange (PMS);
}
Try
{
Con. Open ();
return CMD. ExecuteReader (System.Data.CommandBehavior.CloseConnection);
}
catch (Exception ex)
{
Con. Close ();
Con. Dispose ();
Throw
}
}
}
Perform a return DataTable
public static DataTable executedatatable (String sql, params sqlparameter[] PMS)
{
DataTable dt = new DataTable ();
Using (SqlDataAdapter adapter = new SqlDataAdapter (SQL, CONSTR))
{
if (PMS! = null)
{
Adapter. SelectCommand.Parameters.AddRange (PMS);
}
Adapter. Fill (DT);
}
return DT;
}
public static DataSet Query (String sqlstring,params sqlparameter[] PMS)
{
DataSet ds = new DataSet ();
Using (SqlDataAdapter adapter = new SqlDataAdapter (SQLString, Constr))
{
if (PMS! = null)
{
Adapter. SelectCommand.Parameters.AddRange (PMS);
}
Adapter. Fill (DS);
}
return DS;
}
}
This article is from the "Search in the Wind" blog, please be sure to keep this source http://xingcheng.blog.51cto.com/3693811/1741849
SqlHelper take doctrine--gradual improvement