So I am practicing using a databases with ASP.Net…
I have two datatable columns from Northwind database. One is Product.ProductID and the other is Product.UnitsInStock. I need to compare that with a collection (SortedList) of objects. Essentially comparing variables Product ID and quantity(client side). The objects are a ICollection Value saved in a Session["cart"].
How can I compare the variables I have of product id and units in stock against the DataTable columns 1 is Products.ProductID and second column is Products.UnitsInStock?
Here is the query and roughly how I thought I could grab these variables from the database.
DataTable dt = new DataTable();
if (dt.Columns.Count != 0 &&
dt.Rows.Count != 0)
{
int quantityOfUnit = 0;
int productID = 0;
for (int index = 0; index < dt.Columns.Count; index++)
{
if (index == indexOfUnitsInStock)//indexOfUnitsInStock = 1
{
quantityOfUnit = int.Parse(dt.Rows[0][index].ToString());
}
else//index = 0
{
productID = int.Parse(dt.Rows[0][index].ToString());
}
}
Building a new query:
foreach (object items in ((ShoppingCart)Session["cart"]).Values)
{
OleDbConnection conn = new OleDbConnection((string)Application["DBConnectionString"]);
string selectionString =
"SELECT Products.ProductID, Products.UnitsInStock " +
"FROM Products" +
"WHERE Products.ProductID = " +
((ShoppingCart)Session["cart"]).Values;
DataTable dt = new DataTable();
try
{
OleDbCommand cm = new OleDbCommand(selectionString, conn);
OleDbDataAdapter da = new OleDbDataAdapter();
da.SelectCommand = cm;
da.Fill(dt);
da.Dispose();
}
catch(Exception ex)
{
txtUnderstockedItems.Text = "There was a problem connecting to the database: " + ex.Message ;
}
finally
{
conn.Close();
}
}
Firstly, you generally do not want to concatenate SQL in the way you are doing. Use parameterized SQL. If these are Integer values, you can cast them to integers and then put them in the query and achieve a similar result.
If ShoppingCart.Values is a collection, then you have a few choices.
Out of the 3, the third would be my preference as its safer and probably easier to maintain over the long run.
An example of #1 would be something like this…