update table inside for loop - c#

I am trying to update a mysql table while inside a c# for loop and a if statement well a few if statements. While running with a break point it will run the executenonquery once but the next loop it does not hit that. Even when i does hit the nonquery it does not change the table information.
the ffi string is the name of the column in my table and string val is what i want to put in. I know this is not the safe way to do it but I will change it when i can get it working the way it should.
Updated code it now runs the NONQUERY every time it should but still not updating the table
Code:
for (a = 0; a <= z; a++)
{
if (ds3.Tables[0].Rows[a][1].ToString() == dataGridView1.Rows[i].Cells[0].Value.ToString())
{
if (ds3.Tables[0].Rows[a][2].ToString() == dataGridView1.Rows[i].Cells[1].Value.ToString())
{
if (ds3.Tables[0].Rows[a][3].ToString() == dataGridView1.Rows[i].Cells[2].Value.ToString())
{
MessageBox.Show("We have a match " + dataGridView1.Rows[i].Cells[0].Value.ToString() + " " + dataGridView1.Rows[i].Cells[1].Value.ToString() + " " + dataGridView1.Rows[i].Cells[t].Value.ToString());
try
{
string ffi = textBox1.Text;
decimal val = decimal.Parse(dataGridView1.Rows[i].Cells[t].Value.ToString());
MySqlCommand cmd = new MySqlCommand("Update spt_results SET " + ffi + " = " + val + " where project_Id =" + dataGridView1.Rows[i].Cells[0].Value.ToString() + "",connection2);
//cmd.Connection = connection2;'
// cmd.Connection.Open();
cmd.ExecuteNonQuery();
//cmd.Connection.Close();
}
catch
{
}
The message box does show every loop and the connection2.open will run everytime
Thank you for looking and your help
The update string looks like "update spt_results SET FFI 300 = '15' where project_Id =AAA007" when it runs
Brent

Look at your code:
MySqlCommand cmd = new MySqlCommand();
cmd.CommandText = // ... snip SQL injection invitation
connection2.Open();
cmd.ExecuteNonQuery();
connection2.Close();
The MySqlCommand has no connection. You're opening and closing a connection, but it's got nothing to do with the command. I'd actually expect cmd.ExecuteNonQuery() to throw an exception because it has no connection...
Note that you should use using statements for the command and connection, to ensure that all the resources get cleaned up even in the face of an exception.

use cmd.Connection = connection2; just after connection2.Open();.
When you trying to execute the cmd.ExecuteNonQuery(), it is raising the error for no Connection bounded with the Command and error is caught in catch block. You didn't came to know because you have not doing anything in catch block for the errors.

If uncomment your code: The connection is open correctly and your code should work. But I'd suggest you to open connection once, before the loop, and close it at the end.
Another point is that you catched ALL exceptions, it is not good. The problem can be with the query, try to run "update spt_results SET FFI 300 = '15' where project_Id =AAA007" in the console or another MySQL client. It will throw an error. The field name 'FFI 300' must be quoted because it contains a white space and the value 'AAA007' must be quoted as a string literal. Try this query -
UPDATE spt_results SET `FFI 300` = '15' WHERE project_Id = 'AAA007'

Related

select record from database and show the value on corresponding row value

i got stack with im doing, i have a query that select the minimum value of my quantity, the code running fine for first query B value has a result which is correct from the record, my problem is the second OleQuery the debugging stop in OledDBDatareader and jump into another event. can someone figure our what is the problem?
MyConN.Open();
OleDbCommand OlCmd = new OleDbCommand("Select min(Cqty) from stocks", MyConN);
OleDbDataReader OdR = OlCmd.ExecuteReader();
if (OdR.Read())
{
string B = OdR[0].ToString();
if (B == "")
{}
else
{
string ItemDisc;
string OleQuery = "select *from stocks where Cqty='" + B + "'";
OleDbCommand OlCmdQuery =new OleDbCommand(OleQuery, MyConN);
OleDbDataReader DrQuery = OlCmdQuery.ExecuteReader();
while(DrQuery.Read())
{
ItemDisc = (DrQuery["ItemDesc"].ToString());
}
DrQuery.Close();
DialogResult Result1 = MessageBox.Show("The System detects " + ItemDisc + " product with less than 10 quantity remaining " + Environment.NewLine + " Please check with the suppliers and request orders", "System Message", MessageBoxButtons.OKCancel, MessageBoxIcon.Information);
if (Result1==DialogResult.OK)
{
//some message here
}
}
MyConN.Close();}
Edit: After checking the record in my database and found out that the value is numeric, in my second query i only remove the single quote and the query response as i want.
I think your problem is that you use simultaneously two active dataReaders and this may cause an Exception. Perhaps this is why debugging it goes to another event, because an unhandled exception occurs and continues executing without giving any info (??)
Try adding this code to your database connection string and let me know if it works properly now.
MultipleActiveResultSets=true
Another option is get first reader into a dataset, close the datareader and iterate the dataset in the second bucle.
Hope it helps!

MySQL server error - You have an error in your SQL syntax

I'm trying to update a Database table and getting the error
"MySql.Data.MySqlClient.MySqlException: 'You have an error in your SQL
syntax; check the manual that corresponds to your MySQL server version
for the right syntax to use near 'group='superadmin' WHERE
identifier='steam:steam:1100001098b5888'' at line 1'"
// Creates query to run
public void UpdateInfo(String jobTitle, int jobGrade, String adminLevel, String identifier) {
// Opens the database connection if it's not already open
if (!(databaseConnected)) {
openConnection();
}
// Creates query to run
String query = "UPDATE " + table + " SET job=#jobTitle, job_grade=#jobGrade, group=#adminLevel WHERE identifier=#identifier";
// Makes a new command
MySqlCommand cmd = new MySqlCommand(query, connection);
// Replaces the # placeholders with actual variables
cmd.Parameters.AddWithValue("#jobTitle", jobTitle);
cmd.Parameters.AddWithValue("#jobGrade", jobGrade);
cmd.Parameters.AddWithValue("#adminLevel", adminLevel);
cmd.Parameters.AddWithValue("#identifier", identifier);
// Executes it and if it's...
if (cmd.ExecuteNonQuery() > 0) {
// Successful
MessageBox.Show("Successfully updated information");
closeConnection();
return;
} else {
// Not successful
MessageBox.Show("Error with updating information!");
// Closes the connection again to prevent leaks
closeConnection();
return;
}
}
I tried your query on https://sqltest.net/ and noticed it highlighted "group" when I tried to create the table. I'm wondering if the problem might be the usage of "group" as a column name since it's a reserved word.
Is it possible to try renaming the column to group_level or adding back ticks around 'group' or "group" and seeing if that works?
So for example
'group'=#grouplevel
I found this thread and this thread on renaming the column where they had issues with "group" as a column name. Adding backticks seemed to solve both problems.
EDIT: As per OP, double quotes (") solved the issue instead of single. Edited answer to include.
Try change query like this
String query = "UPDATE " + table + " SET job='#jobTitle', job_grade=#jobGrade, group='#adminLevel' WHERE identifier='#identifier'";
if you input String value with query, you need to use 'this' for work
I hope this will work for you.
if not, you can use String.Format for that like this.
String Query = String.Format("Update `{0}` Set job='{1}', job_grade={2}, group='{3}' Where identifier='{4}'", table, jobTitle, jobGrade, adminLevel, identifier);

Update in SQL query doesn't work c#

I want to update data in my SQL Server table, this code here works fine in my other project but when I copied it to other project it doesn't work anymore.
Here's my code:
con.Open();
float prc = float.Parse(textBox4.Text);
int sum = int.Parse(textBox3.Text);
string sql = "UPDATE LIB_INVENTORY set PRICE=(" + prc + "), QUANTITY=([QUANTITY]) +
(" + sum + "), BSTATUS='" + textBox5.Text + "' where BOOKNAME='"
+ textBox1.Text + "' and PUBLISHER='" + textBox2.Text + "'";
SqlCommand cmd = new SqlCommand(sql, con);
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("One item updated updated!");
It runs successfully but when I checked the table no data has been successfully updated. I checked my code but it is really the same as my other project that works fine. Can somebody help me?
if no error is there then it means where clause is not fulfilling. i think your has typed like :
where BOOKNAME='"<spaace>+ textBox1.Text+<spaace>"' and PUBLISHER='"<spaace>+ textBox2.Text +<spaace>"'";
so just erase space and
try this out.
string sql = "UPDATE LIB_INVENTORY set PRICE=("+prc+"), QUANTITY= ([QUANTITY]) + ("+sum+"), BSTATUS='"+textBox5.Text+"' where BOOKNAME='"+textBox1.Text+"' and PUBLISHER='"+textBox2.Text+"'";
as suggested you should really use parameters for your sql query. On top of this do the following :
SqlCommand cmd = new SqlCommand(sql, con);
int nbrUpdates = cmd.ExecuteNonQuery();
con.Close();
if (nbrUpdates>0) MessageBox.Show("One item updated updated!");
else MessageBox.Show(sql);
You can then check if the string in the sql is correct.
Also log in to your database manually and check if the data you want to update is in fact there.
If it is and the update still does not work, make your code do a select statement for the data you want to update. You still might be accessing the wrong database.
Now to start using sql with parameters like you are supposed to read this :
http://www.csharp-station.com/Tutorial/AdoDotNet/lesson06

Delete query won't work

I'm trying to remove a row from the database that has the same ART as is selected in the combobox. I had it working before but when I changed the database it was supposed to delete it from it stopped working and gave me a error message. I did change the database connection etc acording to the database change.
The error message (Hoping image works)
I don't know why it says "conversion failed when converting the varchar value 'R06018' to data type int" since I don't have a value of R06018 anywhere in the code, nor is it the selected row.
the code I tried after the delete stopped working, it's just the delete without any thing extra (I know it doesn't dispose but the program crashes when it tries to read, and it's just for finding the issue)
try
{
SqlCommand inkoopartdelete = new SqlCommand("delete from ART where ART=" + artnr.SelectedItem + "", Connectie.connMEVO);
drMEVO = inkoopartdelete.ExecuteReader();
MessageBox.Show(this.artnr.SelectedItem + " verwijderd.");
}
catch (Exception e) { MessageBox.Show("" + e); }
The old code after I changed the db connection (set as comment since I tried a smaller bit of code for the delete)
//SqlCommand inkoopdelete = new SqlCommand("delete from ART where ART=#art", Connectie.connMEVO_ART);
//inkoopdelete.Parameters.Add("#art", SqlDbType.VarChar).Value = artnr.SelectedItem;
//drMEVO = inkoopdelete.ExecuteReader();
//try
//{
// while (drMEVO.Read())
// { }
// MessageBox.Show(this.artnr.SelectedItem + " verwijderd.");
//}
//catch (SqlException v)
//{
// MessageBox.Show("" + v);
//}
//inkoopdelete.Dispose();
I hope any of you could help me, since I can't find the issue.
Found the issue, see accepted awnser for error in test code, real error seems to be me reading over a part of the code -_- ...srry
If the ART field is of type nvarchar then, if you really want to use string concatenations, you should enclose your string value in single quotes and write
SqlCommand inkoopartdelete = new SqlCommand(#"delete from ART
where ART='" + artnr.SelectedItem + "'", Connectie.connMEVO);
That's a valid enough reason to revert as soon as possible to use a parameterized query as you have initially. Other reasons to avoid this is the fact that if your value has an embedded single quote the Whole text becomes syntactically wrong. And, finally, string concatenation is the open door for Sql Injection Attacks
A last note. If you want to execute a query like DELETE/INSERT or UPDATE do not use ExecuteReader. It works, but it is not necessary to build an SqlDataReader for that kind of queries. Just use
int affectedRows = inkoopartdelete.ExecuteNonQuery();
Change below statement :
You have to give single quote.
SqlCommand inkoopartdelete = new SqlCommand("delete from ART where ART='" + artnr.SelectedItem + "'", Connectie.connMEVO);

ExecuteNonquery returns 0

In my c# application i am trying to delete a record and i am returning result of the executenonquery to check the deletion is exactly happening as below.
rowsAffected = db.ExecuteNonQuerySQL(
#"DELETE FROM relation WHERE parent_itemid = " + SourceThingId + " AND " +
" child_itemid = " + ThingId + " AND " +
" relation_typeid = " + RelationTypeId);
And the executenonquery is definesd as below,
using (SQLiteTransaction dbtrans = conn.BeginTransaction())
{
SQLiteCommand cmd = conn.CreateCommand();
cmd.CommandText = sqlExpr;
cmd.CommandType = CommandType.Text;
ireturn = cmd.ExecuteNonQuery();
dbtrans.Commit();
}
return ireturn;
But when i am executing its not deleting and the value returns 0.The databse used is sqlite.
Do any one have idea why it happens.Please help.
Thanx in advance.
Well it certainly sounds like the record simply isn't there. You should debug this by running a SELECT * with the same query, and see whether you get any results back.
You should also stop putting your values directly into SQL, and instead use parameterized SQL. That will give a better separation of code and data, avoid SQL injection attacks, and avoid conversion issues (particularly with date/time values).

Categories