I am getting an error while updating the data, the error says: "Syntax error (missing operator) in query expression '[Code] IN('."
Here is the code where i am getting an error at:
OleDbDataReader dReader = cmd.ExecuteReader();
Here is the full code of the function that the error is appear:
private void UpdateQuantity()
{
int index = 0;
string command = "UPDATE [Seranne] SET [Quantity] ='" + newVal + "' WHERE [Code] IN(";
OleDbConnection conn = new OleDbConnection(connectionString);
conn.Open();
OleDbCommand cmd = new OleDbCommand(command, conn);
cmd.Parameters.Add("Quantity", System.Data.OleDb.OleDbType.Integer);
OleDbDataReader dReader = cmd.ExecuteReader();
while (dReader.Read())
{
if (textBoxQuantityContainer[index].Value != 0 && textBoxQuantityContainer[index].Value >= Convert.ToDecimal(dReader["Quantity"].ToString()))
{
newVal = Convert.ToDecimal(dReader["Quantity"].ToString()) - textBoxQuantityContainer[index].Value;
}
System.Media.SoundPlayer sound = new System.Media.SoundPlayer(#"C:\Windows\Media\Windows Notify.wav");
sound.Play();
MessageBox.Show("Updated Successfully", "Success");
index += 1;
}
conn.Close();
dReader.Close();
}
Here is the previous code where the query expression "Code IN":
string query = "SELECT [Quantity], [Description], [Price] FROM [Seranne] WHERE [Code] IN (";
OleDbConnection conn = new OleDbConnection(connectionString);
conn.Open();
if (int.TryParse(this.textBoxCodeContainer[0].Text, out codeValue))
{
query = query + codeValue.ToString();
}
for (int i = 1; i < 17; i++)
{
if (int.TryParse(this.textBoxCodeContainer[i].Text, out codeValue))
{
query = query + "," + codeValue.ToString();
}
}
query = query + ")";
OleDbCommand cmd = new OleDbCommand(query, conn);
cmd.Parameters.Add("Code", System.Data.OleDb.OleDbType.Integer);
cmd.Parameters.Add("Quantity", System.Data.OleDb.OleDbType.Integer);
OleDbDataReader dReader;
dReader = cmd.ExecuteReader();
while (dReader.Read())
{
if (textBoxCodeContainer[index].TextLength != 0)
{
this.textBoxQuantityContainer[index].Maximum = Convert.ToDecimal(dReader["Quantity"].ToString());
this.textBoxDescContainer[index].Text = dReader["Description"].ToString();
this.textBoxSubTotalContainer[index].Text = dReader["Price"].ToString();
}
index += 1;
}
conn.Close();
dReader.Close();
Thanks a bunch!
OK, just keep your code and change this:
for (int i = 1; i < 17; i++) {
if (int.TryParse(this.textBoxCodeContainer[i].Text, out codeValue))
{
query = query + codeValue + ",";
}
}
query = query.TrimEnd(',') + ")";
before proceed you better create integer list out of textBoxCodeContainer values, say it as integers
then
string command = "UPDATE [Seranne] SET [Quantity] =? WHERE [Code] IN(" + string.Join(", " , integers) +")";
Generate integer list as below
List<int> integers = new List<int>();
foreach (var tb in textBoxCodeContainer)
{
int codeValue;
if (int.TryParse(tb.Text, out codeValue))
{
integers.Add(codeValue);
}
}
Related
I have a script that connects itself with a mysql server and makes an sql query if I press a button.
My code:
try
{
MySqlConnection c = new MySqlConnection("Server=****;Database=*****;Uid=****;Pwd=y u no want to know ma pw;");
MySqlCommand cmd = new MySqlCommand("DELETE FROM users WHERE username = '" + textBox1.Text + "'", c);
MySqlDataReader myReader;
c.Open();
myReader = cmd.ExecuteReader();
int cnt = 0;
while(myReader.Read())
{
cnt = cnt + 1;
}
if (cnt == 1)
{
MessageBox.Show("Benutzer erfolgreich entfernt, Sir!");
}
}
catch(Exception ex)
{
MessageBox.Show("Benutzer konnte nicht entfernt werden.\n\n" + ex.ToString());
}
Why isn't the message box showing?
You need to use the ExecuteNonQuery() method of your MySqlCommand object, which will return the row(s) affected - which i suspect you are looking for. A DELETE statement will not return a resultset, only the records affected.
using(MySqlConnection c = new MySqlConnection("Server=**;Database=***;Uid=**;Pwd=**;"))
{
using (MySqlCommand cmd = new MySqlCommand("DELETE FROM users WHERE username = #name"))
{
var userParam = new MySqlParameter();
userParam.Name = "#name";
userParam.Value = textbox1.Text;
cmd.Parameters.Add(userParam);
c.Open();
var recordsAffected = cmd.ExecuteNonQuery();
c.Close();
if (recordsAffected == 1)
{
MessageBox.Show("Benutzer erfolgreich entfernt, Sir!");
}
}
}
I have to retrieve the names and the schemas of old tables for creating the new tables in new database within a program. I wrote this procedure which is working. In first part I get the names of tables and store it in MyArray and the in second part I put this names in query string. But in the second part I get in first read the name of table and the following data is the schema.
Is there a solution like this:(this is not working I tried :)
MySqlCommand cmd = new MySqlCommand("SHOW * CREATE TABLE " + DbName, conn);
My function is there:
private int CopySchemas(string pathname)
{
string [] MyArray = new string[11];
int index = 0;
using (MySqlConnection conn = new MySqlConnection(connstr))
{
using(MySqlCommand cmd = new MySqlCommand("SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE = 'BASE TABLE' AND TABLE_SCHEMA='" + DbName+"'",conn))
{
conn.Open();
try
{
MySqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
MyArray[index] = reader.GetValue(0).ToString();
++index;
}
reader.Dispose();
}
catch (MySqlException e)
{
MessageBox.Show(e.Number.ToString() + " -> " + e.Message.ToString());
return 0;
}
}
for (int i = 0; i < MyArray.Length; ++i)
{
string tblname = MyArray[i];
string fname = pathname +"\\" + tblname + ".sql";
MySqlCommand cmd = new MySqlCommand("SHOW CREATE TABLE " + DbName + "." + tblname, conn);
MySqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
string fname = pathname +"\\" + reader.GetValues(0) + ".sql";
string schema = reader.GetValue(1).ToString();
File.WriteAllText(fname,schema);
}
reader.Dispose();
}
}
return index;
}
Finally I sawed that for each connection must have only one reader.
So I opened two connections and for each connection I associated a reader. So I don't use an array for storing the tables names I use only the second reader where I get the tables names and schemas.
Here is the code:
private int CopySchemas(string pathname)
{
int index = 0;
MySqlConnection conn1 = new MySqlConnection(PublicVariables.cs);
using (MySqlConnection conn = new MySqlConnection(PublicVariables.cs))
{
using (MySqlCommand cmd = new MySqlCommand("SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE = 'BASE TABLE' AND TABLE_SCHEMA='" + PublicVariables.DbName + "'", conn))
{
conn.Open();
conn1.Open();
try
{
MySqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
string tblname = reader.GetValue(0).ToString();
MySqlCommand cmd1 = new MySqlCommand("SHOW CREATE TABLE " + PublicVariables.DbName + "." + tblname, conn1);
MySqlDataReader reader1 = cmd1.ExecuteReader();
while (reader1.Read())
{
string fname = pathname + "\\" + reader1.GetValue(0).ToString() + ".sql";
string schema = reader1.GetValue(1).ToString();
File.WriteAllText(fname, schema);
}
reader1.Dispose();
++index;
}
}
catch (MySqlException e)
{
MessageBox.Show(e.Number.ToString() + " -> " + e.Message.ToString());
return 0;
}
}
}
return index;
}
I got the problem. I want to update the data to the database, but the database won't update.
Here is the code:
else if (firstForm.textBox1.Text == "Seranne")
{
string query = "SELECT [Quantity], [Description], [Price] FROM [Seranne] WHERE [Code] IN (";
OleDbConnection conn = new OleDbConnection(connectionString);
conn.Open();
if (int.TryParse(this.textBoxCodeContainer[0].Text, out codeValue))
{
query = query + codeValue.ToString();
}
for (int i = 1; i < 17; i++)
{
if (int.TryParse(this.textBoxCodeContainer[i].Text, out codeValue))
{
query = query + "," + codeValue.ToString();
}
}
query = query + ")";
OleDbCommand cmd = new OleDbCommand(query, conn);
cmd.Parameters.Add("Code", System.Data.OleDb.OleDbType.Integer);
cmd.Parameters.Add("Quantity", System.Data.OleDb.OleDbType.Integer);
OleDbDataReader dReader;
dReader = cmd.ExecuteReader();
while (dReader.Read())
{
if (textBoxCodeContainer[index].TextLength != 0)
{
this.textBoxQuantityContainer[index].Maximum = Convert.ToDecimal(dReader["Quantity"].ToString());
this.textBoxDescContainer[index].Text = dReader["Description"].ToString();
this.textBoxSubTotalContainer[index].Text = dReader["Price"].ToString();
}
if (textBoxQuantityContainer[index].Value != 0 && textBoxQuantityContainer[index].Value >= Convert.ToDecimal(dReader["Quantity"].ToString()))
{
newVal = textBoxQuantityContainer[index].Value - Convert.ToDecimal(dReader["Quantity"].ToString());
cmd = new OleDbCommand("UPDATE [Seranne] SET [Quantity] ='" + newVal + "' WHERE [Code] IN ('");
}
index += 1;
}
conn.Close();
dReader.Close();
}
}
private void UpdateQuantity()
{
System.Media.SoundPlayer sound = new System.Media.SoundPlayer(#"C:\Windows\Media\Windows Notify.wav");
sound.Play();
MessageBox.Show("Updated Successfully", "Success");
}
private void button1_Click(object sender, EventArgs e)
{
UpdateQuantity();
}
EDIT: (The function UpdateQuantity in below is when the user click Update button) and i am getting an error when i click the Update button, here is the error: Syntax error (missing operator) in query expression '[Code] IN ('.
private void UpdateQuantity()
{
int index = 0;
int codeValue = 0;
string query = "SELECT [Quantity], [Description], [Price] FROM [Seranne] WHERE [Code] IN (";
OleDbConnection conn = new OleDbConnection(connectionString);
OleDbDataReader dReader;
OleDbCommand cmd = new OleDbCommand(query, conn);
conn.Open();
cmd.Parameters.Add("Quantity", System.Data.OleDb.OleDbType.Integer);
dReader = cmd.ExecuteReader();
if (textBoxQuantityContainer[index].Value != 0 && textBoxQuantityContainer[index].Value >= Convert.ToDecimal(dReader["Quantity"].ToString()))
{
cmd = new OleDbCommand("UPDATE [Seranne] SET [Quantity] ='" + newVal + "' WHERE [Code] IN (", conn);
if (int.TryParse(this.textBoxCodeContainer[0].Text, out codeValue))
{
query = query + codeValue.ToString();
}
for (int i = 1; i < 17; i++)
{
if (int.TryParse(this.textBoxCodeContainer[i].Text, out codeValue))
{
query = query + "," + codeValue.ToString();
}
}
query = query + ")";
newVal = textBoxQuantityContainer[index].Value - Convert.ToDecimal(dReader["Quantity"].ToString());
cmd.ExecuteNonQuery();
System.Media.SoundPlayer sound = new System.Media.SoundPlayer(#"C:\Windows\Media\Windows Notify.wav");
sound.Play();
MessageBox.Show("Updated Successfully", "Success");
}
index += 1;
dReader.Close();
conn.Close();
}
private void button1_Click(object sender, EventArgs e)
{
UpdateQuantity();
}
Above code all worked, excepts for updating the Quantity to the database. What I mean is, I set the Quantity in database to 100, when I set Quantity to 10 in my program and update it, the database should be update the Quantity to 90 (because 100 - 10), but it is still at 100.
Could I wrong somewhere?
Here is the link of the screenshots: (ScreenShot 1) https://www.dropbox.com/s/rph5iuh371rc9ny/Untitled.png
(ScreenShot 2) https://www.dropbox.com/s/5q8pyztqy7ejupy/Capture.PNG
In the Screenshot 1, I already set the quantity to 10 and the messagebox show that the data has been updated successfully and the data in the database supposed to be 90 (because 100-10). But, in the Screenshot 2 where the database is, the Quantity still at 100.
Thanks in advance!
Your update query
cmd = new OleDbCommand("UPDATE [Seranne] SET [Quantity] ='" + newVal + "' WHERE [Code] IN ('");
doesn't appear to be completed in the code you have posted. My guess is that you are getting a syntax error which your code is not trapping and displaying.
I can retrieve data from the database and it works now, but only on the first line (both description and code are correct and based on the database).
On the second line, the description is not based on the database, however it display the description for the first line, even though the code for first and second line are different. How do I fix that?
Here is some code:
private void UpdateDatas()
{
int codeValue = 0;
OleDbDataReader dReader;
OleDbConnection conn = new OleDbConnection(connectionString);
conn.Open();
OleDbCommand cmd = new OleDbCommand(
"SELECT [Description], [Price] FROM [Data] WHERE [Code]=#Code", conn);
cmd.Parameters.Add("Code", System.Data.OleDb.OleDbType.Integer);
cmd.Parameters.Add("Code", System.Data.OleDb.OleDbType.Integer);
if (int.TryParse(this.textBoxCodeContainer[0][0].Text, out codeValue))
{
cmd.Parameters["Code"].Value = codeValue;
}
else if (int.TryParse(this.textBoxCodeContainer[0][1].Text, out codeValue))
{
cmd.Parameters["Code"].Value = codeValue;
}
else
{
MessageBox.Show("Error");
}
dReader = cmd.ExecuteReader();
while (dReader.Read())
{
if (textBoxCodeContainer[0][0].TextLength != 0)
{
this.textBoxDescContainer[0][0].Text = dReader["Description"].ToString();
this.textBoxSubTotalContainer[0][0].Text = dReader["Price"].ToString();
}
if (textBoxCodeContainer[0][1].TextLength != 0)
{
this.textBoxDescContainer[0][1].Text = dReader["Description"].ToString();
this.textBoxSubTotalContainer[0][1].Text = dReader["Price"].ToString();
}
}
dReader.Close();
conn.Close();
}
Here is the image:
Here is the image of the database:
That's because you processes first record twice in your loop, for both text boxes. Try this as a quick fix:
int index = 0;
while (dReader.Read())
{
if (textBoxCodeContainer[0][index].TextLength != 0)
{
this.textBoxDescContainer[0][index].Text = dReader["Description"].ToString();
this.textBoxSubTotalContainer[0][index].Text = dReader["Price"].ToString();
}
index += 1;
}
The second problem, is that you add two values for one parameter (Code) in your query, so the result of the select will contain only one row. You should you the "IN" SQL keyword. The second quick fix would concern your query:
var query = "SELECT [Description], [Price] FROM [Data] WHERE [Code] IN (";
if (int.TryParse(this.textBoxCodeContainer[0][0].Text, out codeValue))
{
query = query + codeValue.ToString();
}
if (int.TryParse(this.textBoxCodeContainer[0][1].Text, out codeValue))
{
query = query + "," + codeValue.ToString();
}
query = query + ")";
OleDbCommand cmd = new OleDbCommand(query, conn);
dReader = cmd.ExecuteReader();
How to parametrize the query with the "IN" clause is another problem - this is just a quick fix to make this work.
i have a table with 3 columns(EmpId,EmpName,EmpSalary).
i am using a prepared statement to retrieve all the data from this table using prepared statement.
here is what i have written...
try
{
SqlCommand cmd = con.CreateCommand();
cmd.CommandText = "SELECT EmpId,EmpName,EmpSalary FROM EmpDetails";
SqlParameter paraId = new SqlParameter();
paraId.ParameterName = "#id";
paraId.SqlDbType = SqlDbType.Int;
paraId.Size = 32;
SqlParameter paraName = new SqlParameter();
paraName.ParameterName = "#name";
paraName.SqlDbType = SqlDbType.VarChar;
paraName.Size = 50;
SqlParameter paraSal = new SqlParameter();
paraSal.ParameterName = "#sal";
paraSal.SqlDbType = SqlDbType.Decimal;
paraSal.Precision = 7;
paraSal.Scale = 2;
cmd.Parameters.Add(paraId);
cmd.Parameters.Add(paraName);
cmd.Parameters.Add(paraSal);
con.Open();
cmd.Prepare();
SqlDataReader dr = cmd.ExecuteReader();
string str = "";
while(dr.Read())
{
string id = dr.GetInt32(0).ToString();
string name = dr.GetString(1);
string sal = dr.IsDBNull(2) ? "is null" : dr.GetDecimal(2).ToString();
str += id + "\t" + name + "\t" + sal + "\n";
}
MessageBox.Show(str);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
if (con.State == ConnectionState.Open)
con.Close();
}
but i am getting an error as follows :
"The parameterized Query expects the parameter #id , which was not supplied."
What mistake am i doing here..??
Please use cmd.Parameters.AddWithValue(). Using cmd.Parameters.Add() is deprecated. Google its uses :-)
I checked your code, you will need to supply parameters value like below.
try
{
SqlCommand cmd = con.CreateCommand();
cmd.CommandText = "SELECT EmpId,EmpName,EmpSalary FROM EmpDetails ";
SqlParameter paraId = new SqlParameter();
paraId.ParameterName = "#id";
paraId.SqlDbType = SqlDbType.Int;
paraId.Size = 32;
SqlParameter paraName = new SqlParameter();
paraName.ParameterName = "#name";
paraName.SqlDbType = SqlDbType.VarChar;
paraName.Size = 50;
SqlParameter paraSal = new SqlParameter();
paraSal.ParameterName = "#sal";
paraSal.SqlDbType = SqlDbType.Decimal;
paraSal.Precision = 7;
paraSal.Scale = 2;
//i assume you forgot to setup parameter values.
paraId.Value = 1;
paraName.Value = "thisName";
paraSal.Value = 343;
cmd.Parameters.Add(paraId);
cmd.Parameters.Add(paraName);
cmd.Parameters.Add(paraSal);
con.Open();
cmd.Prepare();
SqlDataReader dr = cmd.ExecuteReader();
string str = "";
while (dr.Read())
{
string id = dr.GetInt32(0).ToString();
string name = dr.GetString(1);
string sal = dr.IsDBNull(2) ? "is null" : dr.GetDecimal(2).ToString();
str += id + "\t" + name + "\t" + sal + "\n";
}
MessageBox.Show(str);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
if (con.State == ConnectionState.Open)
con.Close();
}