App.config文件:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionStrings>
<add name="sql" connectionString="Data Source=.; Initial Catalog=ItCast;Integrated Security=True;"/>
</connectionStrings>
</configuration>
SQLHelper类文件:
static class SQLHelper
{
private static readonly string constr=ConfigurationManager.ConnectionStrings["sql"].ConnectionString;
/// <summary>
/// 1:返回值为int类型的ExecuteNonQuery方法
/// </summary>
/// <param name="sql"></param>
/// <param name="pms"></param>
/// <returns></returns>
publi cstatic int ExecuteNonQuery(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.ExecuteNonQuery();
}
}
}
/// <summary>
/// 2:返回值类型为object类型的ExecuteScalar方法
/// </summary>
/// <param name="sql"></param>
/// <param name="pms"></param>
/// <returns></returns>
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();
}
}
}
/// <summary>
/// 3:返回值为SqlDataReader类型的ExecuteReader方法
/// </summary>
/// <param name="sql"></param>
/// <param name="pms"></param>
/// <returns></returns>
public static SqlDataReader ExecuteReader(stringsql, params SqlParameter[] pms)
{
SqlConnection con=new SqlConnection(constr);
using(SqlCommand cmd=new SqlCommand(sql,con))
{
if (pms!=null)
{
cmd.Parameters.AddRange(pms);
}
con.Open();
return cmd.ExecuteReader(System.Data.CommandBehavior.CloseConnection);
}
}
/// <summary>
/// 4:返回值为DataTable类型的ExecuteDataTable方法
/// 使用DataAdapter对象作为中间桥梁传递数据
/// </summary>
/// <param name="sql"></param>
/// <param name="pms"></param>
/// <returns></returns>
public static DataTable ExecuteDataTable(stringsql, params SqlParameter[] pms)
{
using(SqlDataAdapter adapter=new SqlDataAdapter())
{
if (pms!=null)
{
adapter.SelectCommand.Parameters.AddRange(pms);
}
DataTabledt=new DataTable();
adapter.Fill(dt);
returndt;
}
}
}