日期:2014-05-18  浏览次数:21109 次

同时出多个查询结果的代码优化
我一个asp.net页面,一个按钮执行四个项目的查询,分别显示在4个gridview上。我本人写的代码可以出结果似乎有些耗资源,因为不论是 OracleCommand\DataSet\OracleDataAdapter,都申明了4个;不知是否有少费系统资源的写法。请指教。
C# code

  string ConnectionString = "Data Source=**;user=**;password=**;";//写连接串
  OracleConnection conn = new OracleConnection(ConnectionString);//创建一个新连接
  try
  {
   conn.Open();
   OracleCommand cmd1 = conn.CreateCommand();
   OracleCommand cmd2 = conn.CreateCommand();
   OracleCommand cmd3 = conn.CreateCommand();
   OracleCommand cmd4 = conn.CreateCommand();
   cmd1.CommandText = "SELECT ...";
   cmd2.CommandText = "select ...";
   cmd3.CommandText = "select ...";
   cmd4.CommandText = "select ...";
   
   DataSet ds1 = new DataSet();
   OracleDataAdapter oda1 = new OracleDataAdapter();
   oda1.SelectCommand = cmd1;
   oda1.Fill(ds1);

   DataSet ds2 = new DataSet();
   OracleDataAdapter oda2 = new OracleDataAdapter();
   oda2.SelectCommand = cmd2;
   oda2.Fill(ds2);


   DataSet ds3 = new DataSet();
   OracleDataAdapter oda3 = new OracleDataAdapter();
   oda3.SelectCommand = cmd3;
   oda3.Fill(ds3);

   DataSet ds4 = new DataSet();
   OracleDataAdapter oda4 = new OracleDataAdapter();
   oda4.SelectCommand = cmd4;
   oda4.Fill(ds4);

   conn.Close();
   GridView1.DataSource = ds1.Tables[0].DefaultView;
   GridView1.DataBind();
   GridView2.DataSource = ds2.Tables[0].DefaultView;
   GridView2.DataBind();
   GridView3.DataSource = ds3.Tables[0].DefaultView;
   GridView3.DataBind();
   GridView4.DataSource = ds4.Tables[0].DefaultView;
   GridView4.DataBind();




------解决方案--------------------
一个就够了, OracleDataAdapter每次取得一个数据集,可以fill到dataset中,干嘛创建多个,dataset中有个Tables集合
------解决方案--------------------
try
{
DataSet ds=new DataSet();
OracleDataAdapter oda = new OracleDataAdapter(null,conn);
oda1.SelectCommand.CommandText="select 1...";
oda1.Fill(ds,"表名1");
oda1.SelectCommand.CommandText="select 2...";
oda1.Fill(ds,"表名2");
oda1.SelectCommand.CommandText="select 3...";
oda1.Fill(ds,"表名3");
oda1.SelectCommand.CommandText="select 4...";
oda1.Fill(ds,"表名4");
GridView1.DataSource = ds1.Tables["表名1"];
GridView1.DataBind();
GridView1.DataSource = ds1.Tables["表名2"];
GridView1.DataBind();
GridView1.DataSource = ds1.Tables["表名3"];
GridView1.DataBind();
GridView1.DataSource = ds1.Tables["表名4"];
GridView1.DataBind();