DataSet

DataSet是ADO.NET中的核心对象. DataSet包含一组DataTable对象.
每个DataTable对象都有一些子对象DataRow和DataColumn, 表示数据库表中的行和列. 通过这些对象可以获取表,行和列中的所有元素.
DataSet的常见操作是用DataAdapter对象的Fill()方法给它填充数据.
访问DataSet中的表:
1. 按表名访问: thisDataSet.Tables["Customers"]  指定DataTable对象Customers
2. 按索引(索引是基于0的)访问: thisDataSet.Tables[0]  指定DataSet中的第一个DataTable.
访问DataTable的行和列:
1. 在每个DataTable中,都有一个Rows属性, 它是DataRow对象的集合.
myDataSet.Tables["Customers"].Rows[n]
在thisDataSet的DataTable对象Customers中指定行号n-1(索引是基于0的).
2. DataRow对象有一个重载的索引符属性, 允许按列名或列号访问各个列.
thisDataSet.Tables["Customers"].Rows[n]["CompanyName"]

实例:
ContractedBlock.gif ExpandedBlockStart.gif Code
using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.SqlClient;

namespace DataSetReader
{
    
class Program
    {
        
static void Main(string[] args)
        {
            
//string connstring = @"Data Source=ZHANG-1D093B228;Initial Catalog=northwind;User ID=sa;Password=sa";
            
//string connstring = @"Server=.;Integrated Security=True; Database=northwind";
            
//string connstring = @"Server=ZHANG-1D093B228;Integrated Security=True; Database=northwind";
            string connstring = @"Server=localhost;Integrated Security=True; Database=northwind";

            SqlConnection thisconnection 
= new SqlConnection(connstring );
            
string strsql=@"select customerID,ContactName from Customers";
            SqlDataAdapter thisAdapter 
= new SqlDataAdapter(strsql, thisconnection);
            DataSet thisDataSet 
= new DataSet();
            thisAdapter.Fill(thisDataSet, 
"Customers");
            
foreach (DataRow therow in thisDataSet.Tables["Customers"].Rows)
            {
                Console.WriteLine(therow[
"CustomerID"+ "\t" + therow["ContactName"]);
            }
            thisconnection.Close();
            Console.WriteLine(
"Program finished, press Enter/Return to continue:");
            Console.ReadLine();
        }
    }
}

这几种数据库连接方法都可以.

转载于:https://www.cnblogs.com/niuniu1985/archive/2009/09/09/1563601.html

  • 0
    点赞
  • 0
    收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值