日期:2012-06-28  浏览次数:20542 次

使用 ExecuteScalar 方法从数据库中检索单个值(例如一个聚合值)。与使用 ExecuteReader 方法,然后使用 SqlDataReader 返回的数据执行生成单个值所需的操作相比,此操作需要的代码较少。

典型的 ExecuteScalar 查询可以采用类似于下面的 C# 示例的格式:

CommandText = "select count(*) as NumberOfRegions from region";

Int count = (int) ExecuteScalar();
例子:
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SqlClient" %>

<script language="vb" runat="server">
    Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs)
        If Not IsPostBack Then
            Dim dtStartDate As DateTime = DateTime.Now.AddDays(-7)
            Dim dtEndDate As DateTime = DateTime.Now.AddDays(-1)
            startdate.Text = dtStartDate.ToShortDateString
            enddate.Text = dtEndDate.ToShortDateString
            literal1.Text = GetEditionNumber()
        End If

    End Sub

    Function GetEditionNumber()
        Dim conn As SqlConnection = New SqlConnection(ConfigurationSettings.AppSettings("DSN"))
        Dim cmd As SqlCommand = New SqlCommand("SELECT MAX(Id) from Table", conn)
        conn.Open()
        Dim id As String = cmd.ExecuteScalar
        conn.Close()
        Return id
    End Function
</script>

<html>
    <head></head>
    <body>
        <form runat="server">
            <asp:literal id="literal1" runat="server" /><br>
            <asp:TextBox id="startDate"  runat="server"></asp:TextBox><br>
            <asp:TextBox id="endDate"     runat="server"></asp:TextBox>

        </form>
    </body>
</html>Web.Config used in Example<?xml version="1.0" encoding="utf-8" ?>
<configuration>    
    <appSettings>
        <add key="DSN" value="server=localhost;uid=sa;pwd=;Database=pubs"/>
    </appSettings>
</configuration>