Code
//代码说明
//本例没有创建数据集--DataSet ds=new DataSet();
//而是创建了以个表--DataTable dt=new DataTable();
//没有填充数据集---da.Fill(ds,"products");
//而是填充表--da.Fill(dt);
//因为数据表之能保存一张表,所以注意Fill()方法没有接受数据表名作为参数.由于不需要在数据集中查找特定的表,
//所以一下的代码就不必了 DataTable dt=ds.Tables["products"];
//NOTICE:除非确实要在数据集中组织数据表以及定义他们之间的关系,否则使用一个或者多个数据表比数据集更容易编码!并且占用较少的运行时资源!
![](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 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();
}
}
}
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步