ado.net基本操作复习

public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/html";
          //建立一个数据库的连接
            //打开数据库
            //建立一个数据库的命令
            //输入命令的文本
            //执行这个命令
            //得到其结果
            //对结果进行处理
            //...还是linq方便
            SqlConnection conn = new SqlConnection("Data Source=.;Initial Catalog=图库;Integrated Security=True");
            try
            {
                
                conn.Open();
                context.Response.Write("成功打开数据库:图库");
                SqlCommand cmd = conn.CreateCommand();
                cmd.CommandText="select 文件名 from 图片库";
                
                SqlDataReader reader = cmd.ExecuteReader();

                while (reader.Read())
                {
                    context.Response.Write(reader.GetString(reader.GetOrdinal("文件名")));
                    context.Response.Write("<br/>");
                }
            }
            catch (Exception e)
            {

                context.Response.Write(e.Message);
            }
            finally {
                conn.Close();
            }
        }
其实只是想得到这个文件名字段所包含的字符串集合,一开始在第一句中
context.Response.ContentType = "text/html";
写成了"image/jpeg",结果文本显示出来总有问题

image

http报文的类型不对,显示自然不正确!

GetOrdinal,Ordinal:

ordinal numeral 序数词 ; 序数

ordinal type [计] 顺序类型 ; 有序型 ; [计] 序数型式 ; [计] 序数类型

Ordinal numbers 序数词 ; 序数

image

如果要得到一个时间类型的字符串,需要改变一下获取数据的方式:
public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/html";
            SqlConnection conn = new SqlConnection("Data Source=.;Initial Catalog=图库;Integrated Security=true");
            conn.Open();
            SqlCommand cmd = conn.CreateCommand();
            cmd.CommandText = "select 创建时间 from 图片库";
            var reader = cmd.ExecuteReader();
            while (reader.Read())
            {
                context.Response.Write(reader.GetSqlDateTime(0));
                context.Response.Write("<br/>");
            }
            conn.Close();
        }

紫色部分,因为读取的是一个时间类型的数据,所以需要使用GetSqlDateTime方法来获取,因为只有一个字段,所以后面的参数用了0

改成1呢?自然不行,因为读取出来的数据只有1列

索引超出了数组界限。

说明: 执行当前 Web 请求期间,出现未经处理的异常。请检查堆栈跟踪信息,以了解有关该错误以及代码中导致错误的出处的详细信息。

异常详细信息: System.IndexOutOfRangeException: 索引超出了数组界限。

源错误:


行 23:             while (reader.Read())
行 24:             {
行 25:                 context.Response.Write(reader.GetSqlDateTime(1));
行 26:                 context.Response.Write("<br/>");
行 27:             }
 
 
posted @ 2011-03-30 22:35  爱玩的安哥  阅读(234)  评论(0编辑  收藏  举报