|
发表于 2013-4-23 12:54:09
|
显示全部楼层
关于命名,各人看法不同,但是最好是根据语义来命名,而不是内部调用的特征。
我简单写了几个方法,里面有重载,也有扩展:
/// <summary>
/// 简单查询数据库
/// </summary>
/// <param name="sqlString">sql查询字符串</param>
/// <returns>返回数据集</returns>
public static DataSet Select(string sqlString)
{
using (SqlConnection cn = new SqlConnection(ConnectionString))
{
SqlDataAdapter da = new SqlDataAdapter(sqlString, cn);
DataSet ds = new DataSet();
da.Fill(ds);
return ds;
}
}
/// <summary>
/// 参数化查询数据库
/// </summary>
/// <param name="sqlString">sql查询字符串</param>
/// <param name="sqlParams">sql查询参数数组</param>
/// <returns>返回数据集</returns>
public static DataSet Select(string sqlString, SqlParameter[] sqlParams)
{
using (SqlConnection cn = new SqlConnection(ConnectionString))
{
if (cn.State != ConnectionState.Open) { cn.Open(); }
SqlDataAdapter da = new SqlDataAdapter();
SqlCommand cmd = new SqlCommand(sqlString, cn);
foreach(SqlParameter m in sqlParams)
{
cmd.Parameters.Add(m);
}
DataSet ds = new DataSet();
da.SelectCommand = cmd;
da.Fill(ds);
if (cn.State != ConnectionState.Closed) { cn.Close(); }
return ds;
}
}
/// <summary>
/// 存储过程查询数据库
/// </summary>
/// <param name="storeProcedure">存储过程名称</param>
/// <param name="sqlParams">存储过程参数数组(可选)</param>
/// <returns>返回数据集</returns>
public static DataSet SelectX(string storeProcedure, params SqlParameter[] sqlParams)
{
using (SqlConnection cn = new SqlConnection(ConnectionString))
{
if (cn.State != ConnectionState.Open) { cn.Open(); }
SqlDataAdapter da = new SqlDataAdapter();
SqlCommand cmd = new SqlCommand(storeProcedure, cn);
cmd.CommandType = CommandType.StoredProcedure;
if (sqlParams != null)
{
foreach (SqlParameter m in sqlParams)
{
cmd.Parameters.Add(m);
}
}
DataSet ds = new DataSet();
da.SelectCommand = cmd;
da.Fill(ds);
if (cn.State != ConnectionState.Closed) { cn.Close(); }
return ds;
}
}
|
|