返回首页
当前位置: 主页 > 数据库 >

使用SqlDataReader读取数据示例-.NET教程,数据库应用

时间:2010-06-11 22:42来源:未知 作者:admin 点击:
% @import namespace=system.data % % @import namespace=system.data.sqlclient % html head title使用 sqldatareader 读取数据示例/title script language=c# runat=server void page_load(object sender, system.eventargs e) { string connection

<% @import namespace="system.data" %>
<% @import namespace="system.data.sqlclient" %>
 

<html>
<head>
  <title>使用 sqldatareader 读取数据示例</title>
    <script language="c#" runat="server">
    void page_load(object sender, system.eventargs e)
   {
    string connectionstring = system.configuration.configurationsettings.appsettings["connectionsqlserver"];
    string sql = "select lastname, firstname from employees";

    sqlconnection thisconnection = new sqlconnection(connectionstring);
    sqlcommand thiscommand = new sqlcommand(sql, thisconnection);
    thiscommand.commandtype = commandtype.text;

    try
    {
     // 打开数据库连接
     thiscommand.connection.open();


 

     // 执行sql语句,并返回datareader对象
     sqldatareader dr = thiscommand.executereader();


 

     // 以粗体显示标题
     mylabel.text = "<b>lastname firstname</b><br>";


 

     // 循环读取结果集
     while(dr.read())
     {
      // 读取两个列值并输出到label中
      mylabel.text += dr["lastname"] + " " + dr["firstname"] + "<br>";
     }
     // 关闭datareader
     dr.close();
    }
    catch(sqlexception ex)
    {
     // 异常处理
     response.write(ex.tostring());
    }
    finally
    {
     // 关闭数据库连接
     thiscommand.connection.close();
    }
   }
  
  </script>
  
</head>

<body>
  <form id="form1" method="post" runat="server">
   <h3>使用 sqldatareader 读取数据示例</h3>
    显示内容:<br>
    <asp:label id="mylabel" runat="server"></asp:label>
  </form>
</body>
</html>


 

(责任编辑:admin)
顶一下
(0)
0%
踩一下
(0)
0%
------分隔线----------------------------
发表评论
请自觉遵守互联网相关的政策法规,严禁发布色情、暴力、反动的言论。
评价:
表情:
用户名:密码: 验证码:点击我更换图片
推荐赞助商
推荐内容