How to subtract order of stock? c# MySql - c#

I'm working on a project where the customer can make an order of infinite products, I need my code to read every single product ID of his order.
For this to work, it needs to be in a loop, and I could only find ways to make this without a loop, with finite products on the internet.
I tried using SELECT like this:
string selectCod = "SELECT id FROM order";
MySqlCommand selectCodCmd = new MySqlCommand(selectCod, BDconnection);
reader = selectCodCmd.ExecuteReader();
while (reader.Read())
{
}
reader.Close();
But I can't think of anything to put inside the while, I tried using x = reader[0].ToString(); but I only get the last product ID.
If anyone could help me I would appreciate it
Edit1:
Thanks a lot, It worked! Here's the code if anyone has the same problem in future:
string selectCod = "SELECT id FROM OrderItens";
var selectCodCmd = new MySqlCommand(selectCod, BDconnection);
reader = selectCodCmd.ExecuteReader();
var OrderItensId = new List<string>();
while (reader.Read())
{
OrderItensId.Add(reader["id"].ToString());
}
reader.Close();
foreach(string Code in OrderItensId)
{
string CodeAmount = "SELECT amount FROM OrderItens
WHERE id = "+ Code +"";
var CodeAmountCmd = new MySqlCommand(CodeAmount, BDconnection);
reader = CodeAmountCmd.ExecuteReader();
int OrderAmount = 0;
while (reader.Read())
{
OrderAmount = Int32.Parse(reader[0].ToString());
}
reader.Close();
string UpdateStock = "UPDATE Stock
SET amount = amount - "+OrderAmount+"
WHERE id = "+ Code +"";
var UpdateStockCmd = new MySqlCommand(UpdateStock, BDconnection);
reader = UpdateStockCmd.ExecuteReader();
while (reader.Read()) { }
reader.Close();
}

Well, as i understand, you need to get all the products ids from one specific order right?
With this, you only getting all the orders ids from your table orders
string selectCod = "SELECT id FROM order";
First, you will need the order id and i suppose that you have a table called orderItens or something like that..
Then, you get all the itens for that order with a select like this:
string selectCod = "SELECT id FROM orderItens where orderId = #orderId";
Then just create a loop like this
var orderItensIds = new List<int>();
while (reader.Read())
{
orderItensIds.Add(int.Parse(reader["id"]));
}
reader.Close();
return orderItensIds
There you have a list with all the itens id from your order

You are using it right, you just need to put the code var x = reader[0].ToString(); into while loop to let it get all id in all rows.
For example, I will use a listId list to save Id list. You can use it to calculate or insert later.
string selectCod = "SELECT id FROM order";
MySqlCommand selectCodCmd = new MySqlCommand(selectCod, BDconnection);
reader = selectCodCmd.ExecuteReader();
var listId = new List<int>();
while (reader.Read())
{
var x = reader[0].ToString();
listId.Add(int.Parse(x));
}
reader.Close();
// Use this list to any where you want
listId

Related

Reader losing values after sqlite query

So I'm attempting to read in values from an existing SQLite database and it seems to initially work but after the query it seems to lose the values when I try to read them in.
What am I doing wrong here?
https://www.youtube.com/watch?v=Yvj6BTjts3M
public ObservableCollection<Asset> GetAllAssets()
{
_DbConn.Open();
var command = _DbConn.CreateCommand();
var allAssets = new ObservableCollection<Asset>();
command.CommandText =
#"
SELECT *
FROM asset
";
using (var reader = command.ExecuteReader())
{
while (reader.HasRows)
{
Asset asset = new Asset();
asset.AssetId = reader.GetInt32(0);
asset.AssetTypeId = reader.GetInt32(1);
asset.Name = reader.GetString(2);
asset.FileLocation = reader.GetString(3);
asset.IsCustom = reader.GetBoolean(4);
asset.AssetSectionId = reader.GetInt32(5);
asset.ThumbFileLocation = reader.GetString(6);
allAssets.Add(asset);
}
}
_DbConn.Close();
return allAssets;
}
The method HasRows() returns true if reader contains one or more rows or false if not, but it does not advance reader to the next row.
You must use the method Read():
while (reader.Read())
......................

How SELECT many tags on a Table and save it on a List<string>

I want to know how i can take it all the tags that i have on my table and save it on a list.
string query = "SELECT JobNumber + JobName + JobTag FROM dbo.Cat05Projects WHERE JobNumber = #JobNumber AND JobTag = #JobTag";
SqlCommand command = new SqlCommand(query, cn);
command.Parameters.AddWithValue("JobNumber", JobNumber);
command.Parameters.AddWithValue("JobTag", JobTag);
SqlDataReader reader = command.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
tags.Add(reader[0].ToString());
tags.Add(reader[1].ToString());
tags.Add(reader[2].ToString());
}
}
due to your concatenation (JobNumber + JobName + JobTag) it is not possible to use reader[X].ToString() because just a single string is going to be returned. In order to fetch records properly you have to use comma instead of plus as below.
string query = "SELECT JobNumber , JobName , JobTag FROM dbo.Cat05Projects WHERE JobNumber = #JobNumber AND JobTag = #JobTag";
You did not mention anything about tags data structure, but if i am not mistaken, after getting the correct response, if you are trying to fetch only
JobTag you can use LINQ to filter the final list.
This is what I wanted
query = "SELECT * FROM dbo.Cat05Projects WHERE JobNumber = #JobNumber AND JobTag = #JobTag";
command = new SqlCommand(query, cn);
command.Parameters.AddWithValue("JobNumber", JobNumber);
command.Parameters.AddWithValue("JobTag", JobTag);
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
for (int i = 1; i < reader.FieldCount; i++)
{
lista.Add(reader[i].ToString());
}
}

Retrieve multiple items of data from database into one single label

I want to retrieve multiples values from database and display on one label.
My database design currently is:
courseid scholarshipid course
--------------------------------
1 1 maths
2 1 english
3 1 science
scholarshipid schName
-----------------------
1 moon
2 start
3 light
I would like to retrieve this information into one single label such as
Maths, English, Science
However, now I manage to retrieve one of it which is just maths.
This is my code in code behind:
protected void btnShowDetails_Click(object sender, EventArgs e)
{
string Selectedid = GVFBAcc.SelectedRow.Cells[1].Text;//get user id
int selectedIdtoPass = Convert.ToInt32(Selectedid);
courseBLL getRecord = new courseBLL();
addcourse courseRetrieve = new addcourse();
courseRetrieve = getRecord.getCourseDetail(selectedIdtoPass);
lbCourse.Text = courseRetrieve.course1 + "," + courseRetrieve.course1;
}
in my courseBLL
public addcourse getCourseDetail(int idcourse)
{
addcourse userObj = new addcourse();
courseDAL objtoPass = new courseDAL();
userObj = objtoPass.displayCourseInfo(idcourse);
return userObj;
}
in my DAL
public addcourse displayCourseInfo(int idcourse)
{
string strCommandText = "Select course from course where schokarshipid = #schokarshipid";
SqlCommand cmd = new SqlCommand(strCommandText, conn);
cmd.Parameters.AddWithValue("#scholarshipid", idcourse);
conn.Open();
SqlDataReader myReader = cmd.ExecuteReader();
addcourse userObj = new addcourse();
while (myReader.Read())
{
int sID = Convert.ToInt32(myReader["courseID"].ToString());
string course = myReader["course"].ToString();
userObj = new addcourse(sID, course);
}
myReader.Close();
return userObj;
}
Edited:
public addcourse displayCourseInfo(int idcourse)
{
var courses = new List<addcourse>();
string strCommandText = "Select statement here"
SqlCommand cmd = new SqlCommand(strCommandText, conn);
cmd.Parameters.AddWithValue("#scholarshipid", idcourse);
conn.Open();
SqlDataReader myReader = cmd.ExecuteReader();
while (myReader.Read())
{
int sID = Convert.ToInt32(myReader["scholarshipid"].ToString());
string course = myReader["course"].ToString();
courses.Add(new addcourse(sID,course));
}
myReader.Close();
return courses;
}
I have removed some fields for this purpose so that I will not confuse you
You should return a List<addcourse> from getCourseDetail() and from displayCourseInfo and then you can do this if your addCourse has Course property:
lbCourse.Text = string.Join(", ", courses.Select(x => x.Course));
If the property name is different then change x.Course to that.
So in your reader you will do this
var courses = new List<addcourse>();
while (myReader.Read())
{
int sID = Convert.ToInt32(myReader["courseID"].ToString());
string course = myReader["course"].ToString();
courses.Add( new addcourse(sID, course)) ;
}
return courses;
Your query is also wrong:
Select course, from course ss inner join where courseID =#courseID
So you should fix that and make sure you get the columns you need because right now it is only getting course column and it has syntax errors. Run your query directly against the db using management studio. Once your query works the copy paste it and replace where part with a parameter the way you have it right now.
EDIT
It seems you are still stuck with this so I will give you a more detailed answer; however, you should really study up on some fundamental programming concepts. Anyhow, here it is:
Your code behind:
protected void btnShowDetails_Click(object sender, EventArgs e)
{
string Selectedid = GVFBAcc.SelectedRow.Cells[1].Text;//get user id
// Make sure this is the scholarshipid or the whole thing will
// not work.
int selectedIdtoPass = Convert.ToInt32(Selectedid);
courseBLL courseRetriever = new courseBLL();
// Remember you will get a list here
List<addcourse> courses = courseRetriever.getCourseDetail(selectedIdtoPass);
// This will take the list and separate the course property with a comma and space
var courseNames = string.Join(", ", courses);
// Now assign it to the text property
lbCourse.Text = courseNames;
}
Your BLL:
// See here you are retuning a list
// But you need to pass the scholarshipid so you can get the courses for that scholarshipid
public List<addcourse> GerCourses(int scholarshipId)
{
courseDAL courseRetriever = new courseDAL();
// Get the list
List<addcourse> courses = courseRetriever.GetCourses(scholarshipId);
return courses;
}
Your DAL:
// See here you are retuning a list
// But you need to pass the scholarshipid so you can get the courses for that scholarshipid
public List<addcourse> GetCourses(int scholarshipId)
{
// Make sure your query is correct, see you have spelling mistakes
// it should be scholarshipid not schokarshipid. it has to match the column in your database
// Make sure your table is called course and it has 3 columns: 1. courseid 2. course
// 3. scholarshipid or this query will not work
string strCommandText = "Select courseid, course from course where scholarshipid = #scholarshipId";
SqlCommand cmd = new SqlCommand(strCommandText, conn);
cmd.Parameters.AddWithValue("#scholarshipid", scholarshipId);
conn.Open();
SqlDataReader myReader = cmd.ExecuteReader();
// create a list so we can hold all the courses
List<addcourse> userObjs = new List<addcourse>();
// This will read one row at a time so keep reading until there are no more records
while (myReader.Read())
{
int sID = Convert.ToInt32(myReader["courseid"].ToString());
string course = myReader["course"].ToString();
addcourse userObj = new addcourse(sID, course);
// add it to the list
userObjs.Add(userObj);
}
myReader.Close();
// return the list
return userObjs;
}
A few more tips:
Give your methods more meaningful names. See the names I gave them GetCourses, now it reads like English and it is easy to follow.
Your class addcourse should be called Course. addcourse sounds like an action "add course", that could be a good name for a method if you were adding courses. Also use Pascal notation for class names and method names. Use Camel casing for arguments, parameters and local variables.
Learn how to use the Visual Studio debugger. Go watch some YouTube videos on Visual Studio Debugger.
Create a for loop then add it on the variable you are using

How to use only one select statment for getting multiple values and add them in array

I'm wondering how can I use only a single select mysql statment for getting multiple values from different columns and those values to be added into a array of strings.
For example:
string[] Person = new string[3];
"Select Name,Nickname,Age From TableName";
Person[0] = Name
Person[1] = Nickname
Person[2] = Age
How can I do that?
What have I tried:
string[] Persons = new string[3];
command.CommandText = "Select Name From TableName";
MySqlDataReader myReader;
myReader = commmand.ExecuteReader();
int i = 0;
while (myReader.Read())
{
Persons[i] = myReader.GetString(0);
i++;
}
I know how to get only for 1 column.
Replace the while loop with:
if (myReader.Read())
{
Persons[0] = myReader.GetString(0);
Persons[1] = myReader.GetString(1);
Persons[2] = myReader.GetString(2);
}
myReader.Close();
This only reads one row of data. If you need to read more rows, use a loop again. See Retrieving Data Using a DataReader.

SQL select from database in C#

I have the following code in C#:
string query = "SELECT * FROM Zboruri WHERE cod_aeroport = " + country;
using (var command = new SqlCommand(query, connection))
{
var list = new ArrayList();
var reader = command.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
string data1 = reader.GetString(1);
string data2 = reader.GetString(2);
list.Add(cod_aeroport);
list.Add(data1);
list.Add(data2);
}
}
else
{
string raspuns = "nu este info";
list.Add(raspuns);
}
reader.Close();
connection.Close();
return list;
}
My database table has these columns:
data1(numeric(18,0))
data2(numeric(18,0))
...........
and it giving me error:
Index was outside the bounds of the array.
on this line of code:
string data2 = reader.GetString(2);
How can I fix error?
index starts at 0, not 1
string data1 = reader.GetString(0);
string data2 = reader.GetString(1);
I'll prefer to use the column names retrieve from the table because it gives more description than using index of the column (which is usually the reason for index out of bounds exception)
ex,
string data1 = reader["colName1"].ToString();
string data2 = reader["colName2"].ToString();
side-note: please do use parameters in your query,
string query = "SELECT * FROM Zboruri WHERE cod_aeroport = #country";
and before you call ExecuteReader add this line,
command.Parameters.AddWithValue("#country", country);
var reader = command.ExecuteReader();
The index is zero based, so the first column is 0, the second is 1. You should really use the named version of the columns though;
string data1 = reader["data1"].ToString();
One more thing, you should probably parameterize your query to avoid SQL injection problems, in this case it's almost as simple as your original query and much safer. It also helps the database save quite a bit of time and memory on similar queries;
string query = "SELECT * FROM Zboruri WHERE cod_aeroport = #country";
using (var command = new SqlCommand(query, connection))
{
command.Parameters.AddWithValue("#country", country);
var list = new ArrayList();
...
You should better access them by name, by resolving the index by name using the GetOrdinal() method first, so that the code doesn't break if the query is extended later.
if (reader.HasRows)
{
int data1Index = reader.GetOrdinal("data1");
int data2Index = reader.GetOrdinal("data2");
while (reader.Read())
{
string data1 = reader.GetString(data1index);
string data2 = reader.GetString(data2index);
list.Add(cod_aeroport);
list.Add(data1);
list.Add(data2);
}
}
Note that this is the slightly better approach compared to using the named indexer because it avoids looking up the index on every row.
Also, please do parametrize the query to avoid SQL injection.

Categories

Resources