简体   繁体   中英

How can I use ExecuteScalar in this scenario?

I have this SQL Select statement to select the basket id where the user id equals a specific ID.

I want to store the result of the query in a variable, so I thought I could have done:

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

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

But apparently I need to create a new instance of an SQL Command for it to work, how can I do this for the BasketPage Select Command?

I don't know about your BasketPage , but there is no way you can't perform this query against the underlying database using the ExecuteScalar method. Assuming 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();
        }
    }

Assuming you're using SQL Server have you tried something like

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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