static string str = "server=ETPWQO7ANIFO8OJ\\SQLEXPRESS;database=test-1;uid=ss;pwd=123456";
public static List<T2> ExcuteList<T2>(string strcmd, params SqlParameter[] paras)
{
using (SqlConnection conn = new SqlConnection(str))
{
SqlDataAdapter da = new SqlDataAdapter(strcmd, conn);
da.SelectCommand.Parameters.AddRange(paras);
DataTable dt = new DataTable();
da.Fill(dt);
if (dt.Rows.Count > 0)
{
List<T2> list = new List<T2>();
foreach (DataRow row in dt.Rows)
{
Type t = typeof(T2);
T2 model = (T2)Activator.CreateInstance(t);
PropertyInfo[] proper = t.GetProperties();
foreach (PropertyInfo p in proper)
{
string colName = p.Name;
object colValue = row[colName];
p.SetValue(model, colValue, null);
}
list.Add(model);
}
return list;
}
}
return null;
}
#endregion
#region MyRegion
public static DataTable ExecuteDataTable(string sql, params SqlParameter[] parameters)
{
DataSet ds = new DataSet();
SqlDataAdapter adapter = new SqlDataAdapter(sql, str);
adapter.SelectCommand.Parameters.AddRange(parameters);
try
{
adapter.Fill(ds);
return ds.Tables[0];
}
catch { return null; }
}
#endregion
#region MyRegion
public static int ExecuteNonQuery(string sql, params SqlParameter[] parameters)
{
using (SqlConnection conn = new SqlConnection(str))
{
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
cmd.Parameters.AddRange(parameters);
conn.Open();
return cmd.ExecuteNonQuery();
}
}
}
#endregion
#region MyRegion
public static object ExecuteScalar(string sql, params SqlParameter[] parameters)
{
using (SqlConnection conn = new SqlConnection(str))
{
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
cmd.Parameters.AddRange(parameters);
conn.Open();
return cmd.ExecuteScalar();
}
}
}
#endregion