C# SelectCommand 求解每一行注释
publicstaticDataTableSelect(SqlParameter[]SqlParameter,stringCommandText){SqlConnecti...
public static DataTable Select(SqlParameter[] SqlParameter, string CommandText)
{
SqlConnection conn = new SqlConnection();
conn.ConnectionString = SqlConnStr.ReturnStr(); // 连接数据库
SqlDataAdapter ad = new SqlDataAdapter();
ad.SelectCommand = new SqlCommand();
ad.SelectCommand.Connection = conn;
ad.SelectCommand.CommandType = CommandType.StoredProcedure;
ad.SelectCommand.CommandText = CommandText;
DataTable dt = new DataTable();
try
{
conn.Open();
ad.Fill(dt);
conn.Close();
}
catch (SqlException ex)
{
throw new Exception("检索数据发生错误", ex);
}
finally
{
if (conn.State == ConnectionState.Open)
conn.Close();
}
return dt;
} 展开
{
SqlConnection conn = new SqlConnection();
conn.ConnectionString = SqlConnStr.ReturnStr(); // 连接数据库
SqlDataAdapter ad = new SqlDataAdapter();
ad.SelectCommand = new SqlCommand();
ad.SelectCommand.Connection = conn;
ad.SelectCommand.CommandType = CommandType.StoredProcedure;
ad.SelectCommand.CommandText = CommandText;
DataTable dt = new DataTable();
try
{
conn.Open();
ad.Fill(dt);
conn.Close();
}
catch (SqlException ex)
{
throw new Exception("检索数据发生错误", ex);
}
finally
{
if (conn.State == ConnectionState.Open)
conn.Close();
}
return dt;
} 展开
1个回答
展开全部
建议你在这之前学习一下通过适配器(SqlDataAdapter)进行数据库操作的流程.
这个不在这里讲解了.
/// <summary>
/// 从数据库查找数据
/// </summary>
/// <param name="SqlParameter">查找数据库的条件</param>
/// <param name="CommandText"></param>
/// <returns></returns>
public static DataTable Select(SqlParameter[] SqlParameter, string CommandText)
{
//初始化数据库连接SqlConnection
SqlConnection conn = new SqlConnection();
//获取数据库连接字符串,并赋值给数据库连接.
//SqlConnStr是一个自己写的类,你去你的代码里找吧.
conn.ConnectionString = SqlConnStr.ReturnStr();
//初始化数据库适配器SqlDataAdapter
SqlDataAdapter ad = new SqlDataAdapter();
//初始化数据库适配器的指令SqlCommand
ad.SelectCommand = new SqlCommand();
//为指令配置数据库连接
ad.SelectCommand.Connection = conn;
//设置通过存储过程进行查找.
ad.SelectCommand.CommandType = CommandType.StoredProcedure;
//设置指令的SQL语句.
ad.SelectCommand.CommandText = CommandText;
//初始化一个DataTable,用于保存查询结果.
DataTable dt = new DataTable();
//try,catch,用于处理异常.
try
{
//打开数据库连接.
conn.Open();
//适配器将符合要求的结果装入DataTable中.
ad.Fill(dt);
//关闭数据库连接.
conn.Close();
}
//发生错误后执行的代码.
catch (SqlException ex)
{
//人工抛出异常.
throw new Exception("检索数据发生错误", ex);
}
//最后要执行的内容
finally
{
//如果数据库连接处于打开状态,则关闭数据库连接.
if (conn.State == ConnectionState.Open)
conn.Close();
}
//返回数据库查询结果DataTable
return dt;
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询