繁体   English   中英

在这种情况下如何使用ExecuteScalar?

[英]How can I use ExecuteScalar in this scenario?

我有此SQL Select语句来选择用户ID等于特定ID的购物篮ID。

我想将查询结果存储在一个变量中,所以我想可以做到:

BasketPage.SelectCommand="SELECT BasketID FROM tblBasket WHERE (UserID = '9f96bd94-91b9-4328-8214-4eac179c3a26')"

var BasketID = BasketPage.ExecuteScalar().ToString();

但是显然我需要创建一个SQL Command的新实例才能起作用,如何为BasketPage Select Command做到这一点?

我不知道您的BasketPage ,但是您无法使用ExecuteScalar方法对基础数据库执行此查询。 假设SQL Server:

using (var connection = new SqlConnection(connString))
    using (var command = connection.CreateCommand()) {
        command.CommandText = "select BasketId from tblBasket where UserId = N'9f96bd94-91b9-4328-8214-4eac179c3a26'";
        command.CommandType = CommandType.Text;

        try {
            var basketId = (string)command.ExecuteScalar(); // Assuming BasketId is a string, since you called ToString() in your question.
        } finally {
            command.Dispose();
            connection.Dispose();
        }
    }

假设您正在使用SQL Server,是否尝试过类似

BasketPage.SelectCommand = 
         new SqlCommand("SELECT BasketID FROM tblBasket WHERE (UserID = '9f96bd94-91b9-4328-8214-4eac179c3a26')",
                      "yourconnectionstring");

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM