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

时间:2010-12-06 00:40:35

标签: c# asp.net sql executescalar

我有这个SQL Select语句来选择用户id等于特定ID的篮子ID。

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

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

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

但显然我需要创建一个新的SQL命令实例才能工作,如何为BasketPage Select命令执行此操作?

2 个答案:

答案 0 :(得分:2)

我不知道你的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();
        }
    }

答案 1 :(得分:1)

假设您正在使用SQL Server,您尝试了类似

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