簡體   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