// // author: agile // datetime:5/29/2011 8:59:13 AM // class: SQLHelper // using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data.SqlClient; using System.Configuration; using System.Data; namespace SqlHelper
{ class SQLHelper { public static int ExecuteNonQuery(string sql,params SqlParameter[] parameters) { string conn = ConfigurationManager.ConnectionStrings["conn"].ConnectionString; using (SqlConnection strconn = new SqlConnection(conn)) { strconn.Open(); using (SqlCommand cmd = strconn.CreateCommand()) { cmd.CommandText = sql; foreach (SqlParameter parameter in parameters) { cmd.Parameters.Add(parameter); } return cmd.ExecuteNonQuery(); } } } public static object ExecuteScalar(string sql, params SqlParameter[] parameters) { string conn = ConfigurationManager.ConnectionStrings["conn"].ConnectionString; using (SqlConnection strconn = new SqlConnection(conn)) { strconn.Open(); using (SqlCommand cmd = strconn.CreateCommand()) { cmd.CommandText = sql; foreach (SqlParameter parameter in parameters) { cmd.Parameters.Add(parameter); } return cmd.ExecuteScalar(); } } } public static DataTable ExecuteDataTable(string sql, params SqlParameter[] parameters) { string conn = ConfigurationManager.ConnectionStrings["conn"].ConnectionString; using (SqlConnection strconn = new SqlConnection(conn)) { strconn.Open(); using (SqlCommand cmd = strconn.CreateCommand()) { cmd.CommandText = sql; foreach (SqlParameter parameter in parameters) { cmd.Parameters.Add(parameter); } DataSet dataset = new DataSet(); SqlDataAdapter adapter = new SqlDataAdapter(cmd); adapter.Fill(dataset); return dataset.Tables[0]; } } } } }
使用:
string name = Convert.ToString(SQLHelper.ExecuteScalar("select name from T_persons where id=@id", new SqlParameter("id", 20)));