asp.net中读取数据库数据的方法

1. 使用SqlDataSource

(1)使用SqlDataReader

 1  string  connStr  =  ConfigurationManager.ConnectionStrings[ " ConnStr " ].ConnectionString;
 2  string  selectString  =   " select id from info " ;
 3 
 4  SqlDataSource source  =   new  SqlDataSource(connStr, selectString);
 5  source.DataSourceMode  =  SqlDataSourceMode.DataReader;
 6  SqlDataReader sqlDataReader  =  (SqlDataReader)source.Select(DataSourceSelectArguments.Empty);
 7  while  (sqlDataReader.Read())
 8  {
 9       int  id  =  ( int )sqlDataReader[ 0 ];
10       // 等同于:
11       // int id = (int)sqlDataReader["id"];
12  }

(2)使用DataView

 1  string  connStr  =  ConfigurationManager.ConnectionStrings[ " ConnStr " ].ConnectionString;
 2  string  selectString  =   " select id from info " ;
 3 
 4  SqlDataSource source  =   new  SqlDataSource(connStr, selectString);
 5  source.DataSourceMode  =  SqlDataSourceMode.DataSet;
 6  DataView dv  =  (DataView)source.Select(DataSourceSelectArguments.Empty);
 7  foreach  (DataRowView drv  in  dv)
 8  {
 9       int  id  =  ( int )drv[ 0 ];
10       // int id = (int)drv["id"];
11  }

参考:

SqlDataSource.Select 方法

如何读取DATAVIEW的每一行?


2.使用SqlConnection和SqlCommand

(1)使用SqlDataReader

 1  string  connStr  =  ConfigurationManager.ConnectionStrings[ " ConnStr " ].ConnectionString;
 2  string  selectString  =   " select id from info " ;
 3  using  (SqlConnection conn  =   new  SqlConnection(connStr))
 4  {
 5      SqlCommand cmd  =   new  SqlCommand(selectString, conn);
 6      conn.Open();
 7      SqlDataReader sqlDataReader  =  cmd.ExecuteReader();
 8       while  (sqlDataReader.Read())
 9      {
10           int  id  =  ( int )sqlDataReader[ " id " ];
11           // int id = (int)sqlDataReader[0];
12      }
13      sqlDataReader.Close();
14      cmd.Dispose();
15  }

(2)使用SqlDataAdapter

 1  string  connStr  =  ConfigurationManager.ConnectionStrings[ " ConnStr " ].ConnectionString;
 2  string  selectString  =   " select id from info " ;
 3  using  (SqlConnection conn  =   new  SqlConnection(connStr))
 4  {
 5      SqlDataAdapter adapter  =   new  SqlDataAdapter(selectString, conn);
 6      DataSet ds  =   new  DataSet();
 7      adapter.Fill(ds,  " infotable " );
 8       foreach  (DataRow dr  in  ds.Tables[ " infotable " ].Rows)
 9      {
10           int  id  =  ( int )dr[ " id " ];
11           // int id = (int)dr[0];
12      }
13  }

参考:

C#读取DataSet中的数据 

C#数据库操作的三种经典用法 

谭总《DOT NET程序设计》视频 "ADO.net 2.avi"

转载于:https://www.cnblogs.com/lbsx/archive/2010/10/04/1842102.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值