How can I use ExecuteScalar in this scenario?
-
08-10-2019 - |
Question
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?
Solution
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();
}
}
OTHER TIPS
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");
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow