利用SqlCommand和SqlDataReader对象操作数据库

  
    
using System;
2
using System.Data;
3
using System.Configuration;
4
using System.Collections;
5
using System.Web;
6
using System.Web.Security;
7
using System.Web.UI;
8
using System.Web.UI.WebControls;
9
using System.Web.UI.WebControls.WebParts;
10
using System.Web.UI.HtmlControls;
11
using System.Data.SqlClient; // added by zhangq
12
13
public partial class TestDB : System.Web.UI.Page
14 {
15 private void ReadSingleResult()
16 {
17 // 创建数据连接
18 // 从文件web.config中读取数据库链接字符串
19 string conString = ConfigurationManager.ConnectionStrings[ " DBTESTConnectionString " ].ConnectionString;
20 SqlConnection myCon = new SqlConnection(conString);
21
22 // 创建执行命令
23 SqlCommand myCmd = new SqlCommand( " SELECT TOP 3 * FROM 仓库 ORDER BY 仓库号 DESC " , myCon);
24
25 // 定义dr
26 SqlDataReader dr = null ;
27 try
28 {
29 myCon.Open(); // 打开数据库的链接
30 dr = myCmd.ExecuteReader();
31 ShowData(dr);
32 dr.Close();
33 }
34 catch (Exception ex) { Response.Write(ex.Message); }
35 finally
36 {
37 myCon.Close();
38 }
39 }
40 private void ShowData(SqlDataReader dr)
41 {
42 String str = "" ;
43 for ( int i = 0 ; i < dr.FieldCount; i ++ )
44 {
45 str = str + dr.GetName(i);
46 }
47 str = str + " <br> " ;
48 while (dr.Read())
49 {
50 for ( int i = 0 ; i < dr.FieldCount; i ++ )
51 {
52 str = str + dr[i].ToString();
53 }
54 }
55 Response.Write(str);
56 }
57 protected void Page_Load( object sender, EventArgs e)
58 {
59 ReadSingleResult();
60 }
61 }

你可能感兴趣的:(command)