Code
//先创建数据适配器,
SqlDataAdapter da=new SqlDataAdapter();
da.SelectCommand=new SqlCommand(sql,conn);
//创建和填充数据集
DataSet ds=new DataSet();
da.Fill(ds,"Customers");
//每个查询返回一个数据集,每个结果都保存在单独的DataTable中.第一个显示地命名Customers,第二个表达默认名词为Customers1.
//从数据集的Tables属性获得DataTables对象集合
DataTableCollection dtc=ds.Tables;
在显示第一个表时:
string fl="country='Germany'";//sql where
string srt="CompanyName desc";//sql desc
![ExpandedBlockStart.gif](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
SqlConnection conn = new SqlConnection("server=zhuobin;uid=sa;pwd=zhuobin;database=Northwind");
string sql1 = @"select * from customers ";//Notice:add a space after the string sql1
string sql2 = @"select * from products where unitprice<10";
string sql = sql1 + sql2;
try
{
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = new SqlCommand(sql, conn);
DataSet ds = new DataSet();
da.Fill(ds, "customers");
//Console.WriteLine("I love you !");
//get the table collections
DataTableCollection dtc = ds.Tables;//the tables collections of the ds
//display data from the first table
Console.WriteLine("Result from the customers tables:");
Console.WriteLine("CompanyName".PadRight(20),"ContactName".PadRight(23)+"\n");
//set display filter
string fl = "country='Germany'";
//set sort
string srt = "Companyname";
//display the filtered and sorted data
foreach (DataRow row in dtc["customers"].Select(fl, srt))
{
Console.WriteLine("{0}\t{1}",row["companyname"].ToString().PadRight(25),row["contactname"].ToString());
}
//display the data from the second table
Console.WriteLine("\n-----------------------------------------------------");
Console.WriteLine("The result from products :");
Console.WriteLine("ProductName".PadRight(20),"UintPrice".PadRight(21));
//display data
foreach (DataRow row in dtc[1].Rows)
{
Console.WriteLine("{0}\t{1}",row["productname"].ToString().PadRight(25),row["unitprice"].ToString());
}
}
catch (SqlException ex)
{
Console.WriteLine("The error {0}", ex.Message);
}
finally
{
conn.Close();
}
Console.ReadLine();
}
}
}