// static classes cannot be instantiated
// static classes can be used as convenient containers for sets of methods that only operate on input parameters and do not have to get or set any internal instance fields
// type information for static classes is loaded when programs refer to the class , the static constructor is only called once, and the static class will be stored in memory
// only contains static members
// cannot be instantiated
// will be sealed, cannot be inherited
// cannot contain instance constructors
static class SqlHelper
{//Connection string
private static readonly string constr = ConfigurationManager.ConnectionStrings["sql"].ConnectionString;
#region ExecuteNonQuery returns the number of affected rows, adds, modifies, deletes
public static int ExecuteNonQuery(string sql, params SqlParameter[] pms)
{
using (SqlConnection conn = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
if (pms != null)
{
cmd.Parameters.AddRange(pms);
}
conn.Open ();
//ExecuteNonQuery returns the number of affected rows, add, modify, delete
return cmd.ExecuteNonQuery();
}
}
}
#endregion
#region Execute the query, return the first row and first column
public static object ExecuteScalar(string sql, params SqlParameter[ ] pms)
{
using (SqlConnection conn = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
if (pms != null)
{
cmd.Parameters.AddRange(pms);
}
conn.Open();
//Execute the query, return the first row and the first column
return cmd.ExecuteScalar();
}
}
}
#endregion
#region Read data in streaming mode
public static SqlDataReader ExecuteReader(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);
}
try
{
con.Open();
return cmd.ExecuteReader(System.Data.CommandBehavior.CloseConnection);
}
catch (Exception e)
{
con.Close();
con.Dispose();
throw e;
}
}
}
}
#endregion
#region 表格方式读取数据
public static DataTable ExecuteDataTable(string sql, params SqlParameter[] pms)
{
using (SqlDataAdapter adapter = new SqlDataAdapter(sql, constr))
{
if (pms != null)
{
adapter.SelectCommand.Parameters.AddRange(pms);
}
DataTable dt = new DataTable();
adapter.Fill(dt);
return dt;
}
}
#endregion
}
}
================================================================
App.config
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionStrings>
<add name="sql" connectionString="Data Source=LONG-PC;Initial Catalog=TestDb;Integrated Security = True;"/>
</connectionStrings>
</configuration>