Code

//代码说明

//本例没有创建数据集--DataSet ds=new DataSet();

//而是创建了以个表--DataTable dt=new DataTable();

//没有填充数据集---da.Fill(ds,"products");

//而是填充表--da.Fill(dt);

//因为数据表之能保存一张表,所以注意Fill()方法没有接受数据表名作为参数.由于不需要在数据集中查找特定的表,

//所以一下的代码就不必了  DataTable dt=ds.Tables["products"];

//NOTICE:除非确实要在数据集中组织数据表以及定义他们之间的关系,否则使用一个或者多个数据表比数据集更容易编码!并且占用较少的运行时资源!

 ConsoleApplication1
{
    class Program
    {
        
static void Main(string[] args)
        {
            SqlConnection conn 
= new SqlConnection("Server=zhuobin;uid=sa;pwd=zhuobin;database=northwind");
            String qry 
= @"select productname,unitprice from products where unitprice<20";
            
try
            { 
             
//Open the connection
                conn.Open();
                
//Create the dataAdapter
                SqlDataAdapter da = new SqlDataAdapter();
                da.SelectCommand 
= new SqlCommand(qry,conn);
                
//Create the DataTable
                DataTable dt = new DataTable();
                
//Fill the dataTable
                da.Fill(dt);
                
//Display the data
                foreach (DataRow row in dt.Rows)
                {
                    
foreach (DataColumn col in dt.Columns)
                    {
                        Console.WriteLine(row[col]);
                    } Console.WriteLine(
"".PadLeft(20,'='));
                }

            }
            
catch (SqlException ex)
            {
                Console.WriteLine(
"Error:{0}", ex.Message);
            }
            
finally
            {
                conn.Close();
            }
            Console.ReadLine();
        }
    }
}

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2021-12-11
  • 2022-01-01
  • 2021-12-15
  • 2021-10-31
  • 2021-11-02
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2021-10-06
  • 2022-01-24
  • 2021-11-04
  • 2022-12-23
  • 2021-09-12
  • 2022-12-23
相关资源
相似解决方案