标签:
class SqlHelper { private static string connStr = ConfigurationManager.ConnectionStrings["dbconstr"].ConnectionString; //public static int ExecuteNonQuery(string sql) //{ // using(SqlConnection conn=new SqlConnection(connStr)) // { // conn.Open(); // using (SqlCommand cmd = conn.CreateCommand()) // { // cmd.CommandText = sql; // return cmd.ExecuteNonQuery(); // } // } //} //public static object ExecuteScalar(string sql) //{ // using(SqlConnection conn=new SqlConnection(connStr)) // { // conn.Open(); // using(SqlCommand cmd=conn.CreateCommand()) // { // cmd.CommandText = sql; // return cmd.ExecuteScalar(); // } // } //} //public static DataTable ExecuteDataSet(string sql) //{ // using (SqlConnection conn = new SqlConnection(connStr)) // { // conn.Open(); // using(SqlCommand cmd=conn.CreateCommand()) // { // cmd.CommandText = sql; // SqlDataAdapter adapter = new SqlDataAdapter(cmd); // DataSet dataset = new DataSet(); // adapter.Fill(dataset); // return dataset.Tables[0]; // } // } //} public static int ExecuteNonQuery(string sql,SqlParameter[] parameters) { using (SqlConnection conn = new SqlConnection(connStr)) { conn.Open(); using (SqlCommand cmd = conn.CreateCommand()) { cmd.CommandText = sql; //foreach (SqlParameter param in parameters) //{ // cmd.Parameters.Add(param); //} cmd.Parameters.AddRange(parameters); return cmd.ExecuteNonQuery(); } } } public static object ExecuteScalar(string sql,SqlParameter[] parameters) { using (SqlConnection conn = new SqlConnection(connStr)) { conn.Open(); using (SqlCommand cmd = conn.CreateCommand()) { cmd.CommandText = sql; cmd.Parameters.AddRange(parameters); return cmd.ExecuteScalar(); } } } //public static DataTable ExecuteDataSet(string sql,SqlParameter[] parameters) //{ // using (SqlConnection conn = new SqlConnection(connStr)) // { // conn.Open(); // using (SqlCommand cmd = conn.CreateCommand()) // { // cmd.CommandText = sql; // cmd.Parameters.AddRange(parameters); // SqlDataAdapter adapter = new SqlDataAdapter(cmd); // DataSet dataset = new DataSet(); // adapter.Fill(dataset); // return dataset.Tables[0]; // } // } //} public static DataTable ExecuteDataSet(string sql, params SqlParameter[] parameters)//params长度可变参数 必须是数组 { using (SqlConnection conn = new SqlConnection(connStr)) { conn.Open(); using (SqlCommand cmd = conn.CreateCommand()) { cmd.CommandText = sql; cmd.Parameters.AddRange(parameters); SqlDataAdapter adapter = new SqlDataAdapter(cmd); DataSet dataset = new DataSet(); adapter.Fill(dataset); return dataset.Tables[0]; } } } }
标签:
原文地址:http://www.cnblogs.com/lushixiong/p/4558468.html