照书上改了一下,一个简单的查询结果,用到了
Sqlconnection
Sqlcommand
SqlDataReader
表:Sell
存储过程:GetProduct
========================================
CREATE PROCEDURE  GetProduct
 (
 @strName varchar(50)
 )
AS
 Select @strName=RTRIM(@strName) + '%'
 
SELECT SellID ,ProductName, UnitCost, Number
FROM Sell
WHERE (ProductName like  @strName)

RETURN

GO
=========================================
使用DataReader处理数据库时的流程图
1)使用SqlCommand对象执行sql语句
2)将SqlCommand读取的数据放在DataReader中
3)对DataReader数据进行处理显示

代码:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="conn1.aspx.cs" Inherits="conn1" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    
<title>无标题页</title>
</head>
<body>
    
<form id="form1" runat="server">
    
<div>
        
&nbsp;<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
        
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Search" />
        
<br />
        
<br />
        
<asp:Label ID="Label1" runat="server"></asp:Label></div>
    
</form>
</body>
</html>

CS代码:
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;

public partial class conn1 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        Label1.Text = "";//清空结果
        SqlConnection myconn = new SqlConnection("server=localhost;database=OnNetBookSell;uid=sa;pwd=123");
        //定义command
        SqlCommand mycmd = new SqlCommand();
        mycmd.Connection = myconn;
        mycmd.CommandType  = CommandType.StoredProcedure;
        mycmd.CommandText  = "GetProduct";
        //增加一个参数
        SqlParameter sqlparam = new SqlParameter("@strName", SqlDbType.NVarChar, 50);
        sqlparam.Value = TextBox1.Text;
        mycmd.Parameters.Add(sqlparam);
        myconn.Open();

        //执行并显示
        SqlDataReader myreader = mycmd.ExecuteReader();
        while (myreader.Read())
        {
            Label1.Text += myreader["ProductName"];
            Label1.Text += "<br>";

        }
        myconn.Close();
        myreader.Close();

    }
}


posted on 2006-07-24 15:43  新世代三无人  阅读(1767)  评论(0编辑  收藏  举报