首页 > 开发 > 综合 > 正文

&#101xecuteScalar 方法

2024-07-21 02:22:28
字体:
来源:转载
供稿:网友
使用 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>
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表