public class SqlHlper { public static readonly string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString; //執行增刪改 public stati ...
public class SqlHlper
{
public static readonly string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
//執行增刪改
public static object ExecuteNonQuery(string sql, params SqlParameter[] pms)//SqlParameter需要調用Data.SqlClient
{
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();
}
}
}
//獲取單個數據
public static object ExecteScalar(string sql, params SqlParameter[] pms)
{
object obj = null;
using (SqlConnection conn = new SqlConnection(constr))
{
SqlCommand cmd = new SqlCommand(sql, conn);
conn.Open();
if (pms != null)
{
cmd.Parameters.AddRange(pms);
}
obj = cmd.ExecuteScalar();
}
return obj;
}
//獲取多個數據
public static SqlDataReader GetDataReader(string sql, params SqlParameter[] sps)
{
SqlConnection conn = new SqlConnection(constr);
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
if (sps != null)
{
cmd.Parameters.AddRange(sps);
}
conn.Open();
return cmd.ExecuteReader(CommandBehavior.CloseConnection);
}
}
//查詢多條數據
public static DataTable GetDataTable(string sql, params SqlParameter[] sps)
{
DataTable dt = new DataTable();
using (SqlDataAdapter da = new SqlDataAdapter(sql, constr))
{
if (sps != null)
{
da.SelectCommand.Parameters.AddRange(sps);
}
da.Fill(dt);
}
return dt;
}
}