Update statement does nothing - c#

When I enter a number in the ChbBeds_numericUpDown and click on the "Update" button, it says "Data Updated", but nothing changes in the database
private void ChbUp_button_Click(object sender, EventArgs e)
{
try
{
string statement = "UPDATE ChamberXPavilions SET Beds count = #beds_count WHERE Pav_name = #pav_name AND Chamber_number = #chamber_number";
cmd = new OleDbCommand(statement, conn);
cmd.Parameters.AddWithValue("#pav_name", Chbpav_comboBox.Text);
cmd.Parameters.AddWithValue("#chamber_number", Chb_numericUpDown.Value);
cmd.Parameters.AddWithValue("#beds_count", ChbBeds_numericUpDown.Value);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
MessageBox.Show("Data updated");
showdata();
}
catch(Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
Is the SQL statement wrong ?

Contrary to SQL Server, the OleDB provider for MS Access does NOT work with named parameters - instead, it uses positional parameters.
In your case, you have a SQL statement
UPDATE ChamberXPavilions
SET Beds count = #beds_count
WHERE Pav_name = #pav_name AND Chamber_number = #chamber_number
so you need to also provide the parameters in the same order - first #beds_count, then #pav_name and finally #chamber_number.
So try this for providing the parameter values:
cmd = new OleDbCommand(statement, conn);
cmd.Parameters.AddWithValue("#beds_count", ChbBeds_numericUpDown.Value);
cmd.Parameters.AddWithValue("#pav_name", Chbpav_comboBox.Text);
cmd.Parameters.AddWithValue("#chamber_number", Chb_numericUpDown.Value);
Now, your UPDATE statement should get the proper values and should now work

Related

C# MySQL. Ubable to execute query

private void button4_Click(object sender, EventArgs e)
{
MySqlConnection connection = new MySqlConnection("datasource=localhost;port=3306;Initial Catalog='liblib';Data Source=localhost;username=root;password=admin");
String query = "UPDATE loans SET dataRet=#data1 WHERE loans.idloans = #idloan";
MySqlCommand cmd = new MySqlCommand(query, connection);
int id = Int32.Parse(textBox9.Text);
cmd.Parameters.Add("#data1", MySqlDbType.Date).Value = dateTimePicker1.Value;
cmd.Parameters.Add("#idloan", MySqlDbType.Int32).Value = id;
connection.Open();
if (cmd.ExecuteNonQuery() == 1)
{
MessageBox.Show("Succesful!");
connection.Close();
FIllCard();
}
else
{
MessageBox.Show("Error");
connection.Close();
}
When I execute this UPDATE query in phpmyadmin it works and updates the entry:
UPDATE loans SET dataRet='2017-5-6' WHERE loans.idloans = 23.
But the problem is when I try it in my Form whith parameters. It always returns me "Error" message(ExecuteNonQuery is different from 1), and when I check the database there is no update. The type of the variables in my database are:
idloans - int; dataRet = date;
Check out this post: update a mySQL table using C#, It does not have an answer marked as solution, but the OP of that question has authentication problems after using the code of the first answer, perhaps it works for you

SQL Update statement on Winforms

I'm still learning C#, I wanna ask about Update statement, I got a problem when updating data ... the process is success but data on database doesn't updated.. Did i do some mistake on this?
MySqlConnection con = new MySqlConnection("server=127.0.0.1;database=cproject;Uid=root;Pwd=admin");
MySqlDataAdapter oDA;
DataTable oDT = new DataTable();
MySqlCommand job;
private void button1_Click(object sender, EventArgs e)
{
job = new MySqlCommand("UPDATE barang SET Nama_barang = '"+txtNama+"' AND Jumlah_barang='"+txtStock+"' AND Harga_awal='"+txtBeli+"' AND Harga_jual='"+txtJual+"' WHERE ID = '"+txtIndex+"'", con);
try
{
con.Open();
job.ExecuteNonQuery();
MessageBox.Show("sukses");
con.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
did I do something wrong?
Few Instructions: You are trying the wrong syntax here for SQL UPDATE, IF you have to update more columns then each one should be separated with commas, not with AND, One more thing you have to take care of is that your code opens a wide door for hackers through injection, To close this door you have to use parameterized queries. Another thing( but not sure), The names txtNama, txtStock etc looks like the names of TextBoxes if so you have to use its .Text properties as well. if not use proper naming conventions.
In simple your code should be like the following:
MySqlCommand sqlCommand = new MySqlCommand("UPDATE barang SET Nama_barang =#Nama_barang,Jumlah_barang=#Jumlah_barang,Harga_awal=#Harga_awal,Harga_jual=#Harga_jual WHERE ID =#id", con);
sqlCommand.Parameters.AddWithValue("#Nama_barang", txtNama.Text);
sqlCommand.Parameters.AddWithValue("#Jumlah_barang", txtStock.Text);
sqlCommand.Parameters.AddWithValue("#Harga_awal", txtBeli.Text);
sqlCommand.Parameters.AddWithValue("#Harga_jual", txtJual.Text);
sqlCommand.Parameters.AddWithValue("#id", txtIndex.Text);
try
{
con.Open();
sqlCommand.ExecuteNonQuery();
MessageBox.Show("sukses");
con.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
You can try .Parameters.Add() if the values are of different types,
I believe you have the values coming in from TextBox as the Naming shows txtNama, txtStock So it should be txtNama.Text, txtStock.Text respectively. Another one which I believe it should be is that the Table in the DB would not be all Varchar Field. For Varchar field we need 'Value' but for int or numbers we should not be using 'value' whereas it should be value. So your Query should look like
"UPDATE barang SET Nama_barang = '" + txtNama.Text + "', Jumlah_barang=" + txtStock.Text + ", Harga_awal=" + txtBeli.Text + ", Harga_jual='" + txtJual.Text + "' WHERE ID = " + txtIndex.Text
I am not sure which of the fields are numeric. So I just removed '' for few which I think would be numeric. Now you should use Using Statement and Parameterized Query to care the SQL Injection. and thus your code would look like
private void button1_Click(object sender, EventArgs e)
{
using (SqlConnection connection = new SqlConnection(connectionString))
using (SqlCommand command = connection.CreateCommand())
{
command.CommandText = "UPDATE barang SET Nama_barang = #namabarang, Jumlah_barang = #Jumlahbarang, Harga_awal= #Hargaawal, Harga_jual=#Hargajual WHERE ID = #myID";
command.Parameters.AddWithValue("#namabarang", txtNama.Text);
command.Parameters.AddWithValue("#Jumlahbarang", txtStock.Text);
command.Parameters.AddWithValue("#Hargaawal", txtNama.Text);
command.Parameters.AddWithValue("#Hargajual", txtBeli.Text);
command.Parameters.AddWithValue("#myID", txtJual.Text);
connection.Open();
command.ExecuteNonQuery();
connection.Close();
}
}

C#/sql changing sql parameter with swl parameter

I have a problem with using SQL in c# form and I hope someone can help me here is codes and I wrote as !!!HERE!!! to row of problem.
I want to check textboxes and if they are empty i'll put old variables to updating function but I couldn't make equalization between old and new command.parameters
private void button2_Click(object sender, EventArgs e)
{
string sql = "Update faculty SET fcode=#fcode,fname=#fname,foundationdate=#foundationdate WHERE fcode=#fcodeold";
try
{
SqlCommand command = new SqlCommand(sql, connection);
command.Parameters.AddWithValue("#fcode", textBox1.Text);
command.Parameters.AddWithValue("#fname", textBox2.Text);
command.Parameters.AddWithValue("#foundationdate", dateTimePicker1.Value);
command.Connection = connection;
// command.CommandText = "DELETE FROM faculty WHERE fcode=#fcode";
command.Parameters.AddWithValue("#fcodeold", dataGridView1.CurrentRow.Cells[0].Value.ToString());
command.Parameters.AddWithValue("#fnameold", dataGridView1.CurrentRow.Cells[1].Value.ToString());
command.Parameters.AddWithValue("#foundationdateold", dataGridView1.CurrentRow.Cells[2].Value.ToString());
if (textBox1.Text =="") command.Parameters.["#fcode"].Value= command.Parameters.("#fcodeold").Value;
//!!!HERE!!!
if (textBox2.Text == "") command.Parameters.AddWithValue("#fname", "#fnameold");
if (dateTimePicker1 == null) command.Parameters.AddWithValue("#foundationdate", "#foundationdateold");
command.ExecuteNonQuery();
connection.Close();
MessageBox.Show("Updating success", "Updated", MessageBoxButtons.OK, MessageBoxIcon.Information);
FormFaculty_Load(null, null);
}
catch (Exception error)
{
MessageBox.Show(error.Message);
}
}
Why are you trying to set the parameter like this?:
command.Parameters.["#fcode"].Value = command.Parameters.("#fcodeold").Value
You already have the "value", because you used it earlier:
command.Parameters.AddWithValue("#fcodeold", dataGridView1.CurrentRow.Cells[0].Value.ToString())
Just set this parameter the same way:
command.Parameters.AddWithValue("#fcode", dataGridView1.CurrentRow.Cells[0].Value.ToString())
Don't try to set values from within the query. You have the data in one place, and the query in another. Set the query values from the data.
To summarize:
Remove where you set the parameter earlier in the code:
command.Parameters.AddWithValue("#fcode", textBox1.Text); // remove this line
and conditionally set the parameter based on your logic:
if (textBox1.Text =="")
command.Parameters.AddWithValue("#fcode", dataGridView1.CurrentRow.Cells[0].Value.ToString())
else
command.Parameters.AddWithValue("#fcode", textBox1.Text)

How to get alert when Unique key is violated

protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection myConnection = new SqlConnection("server=VIVID-PC;Integrated Security = True;Database=SchoolDb");
SqlCommand myCommand = new SqlCommand("Command String", myConnection);
myConnection.Open();
string firstText = TextBox1.Text;
string SecondText = TextBox2.Text;
string thirdText = TextBox3.Text;
string fourthText = TextBox4.Text;
myCommand = new SqlCommand("INSERT INTO SchoolDb_Student(StudentName,RollNo,Session,MobileNo)values('" + firstText + "','" + SecondText + "' , '" + thirdText + "','" + fourthText + "')", myConnection);
myCommand.ExecuteNonQuery();
myConnection.Close();
Response.Redirect("/view.aspx");
}
Use command with parameters to pass data to server.
Make sure you dispose connection and command (via using statement)
Store connection strings in config file
Do not create dummy command objects
Here is complete code:
using(var connection = new SqlConnection(connectionString))
using(var command = connection.CreateCommand())
{
command.CommandText =
#"INSERT INTO SchoolDb_Student(StudentName,RollNo,Session,MobileNo)
VALUES (#studentName, #rollNo, #session, #mobileNo)";
command.Parameters.AddWithValue("studentName", TextBox1.Text);
command.Parameters.AddWithValue("rollNo", TextBox2.Text);
command.Parameters.AddWithValue("session", TextBox3.Text);
command.Parameters.AddWithValue("mobileNo", TextBox4.Text);
connection.Open();
try
{
command.ExecuteNonQuery();
}
catch(SqlException e)
{
if (e.Message.Contains("Violation of UNIQUE KEY constraint"))
// you got unique key violation
}
}
Further considerations - improve naming in your code - TextBox1, TextBox2 etc says nothing to reader. Give them appropriate names, like StudentNameTextBox, RollNoTextBox etc. Also good practice is splitting data access and UI logic.
If the database detects a unique key violation, this line
myCommand.ExecuteNonQuery();
will throw an exception. You can catch that exception and proceed with your own code:
try
{
myCommand.ExecuteNonQuery();
}
catch(Exception e)
{
// right here, "something" went wrong. Examine e to check what it was.
}
Please note that your code is vulnerable to SQL injection attacks. You should be using command paramaters instead of building the SQL manually. In addition, you should be using using blocks (see here for details)
ExecuteNonQuery will throw an exception if it's unable to INSERT row into database. In your case, it's most likely an SqlException. Catch it.
use your returnType from ExecuteNonQuery() (Read the remarks part) to detect failure in insertion. you can use the exception or the no. of rows affected part
Try this :
try
{
... your rest of the code
...
int rowsAffected = myCommand.ExecuteNonQuery(); // Most probaboly it will throw exception in case of Unique key violation. If not, still no rows have been affected
if(rowsAffected<1)
{
//your Alert for no records inserted
}
else
{
//your alert for successful insertion
}
}
catch(SqlException ex)
{
//check the exception and display alert
}
finally
{
//release connection and dispose command object
}
As suggested in comment use command param.
try
{
//Your other code
_myCommand.ExecuteNonQuery();
myConnection.Close();
Response.Redirect("/view.aspx");
}
catch(SqlException sqlExc)
{
// Your popup or msg.
}
You also loop for different sql error in catch block.

SQL rows are not being deleted

So I have this code that is designed to delete a row in mySQL server database judging by what is selected in my list box. Here is the code I have to remove the rows:
private void remove_btn_Click(object sender, EventArgs e)
{
try
{
if (Calls_lsb.SelectedItem == null)
MessageBox.Show("Please select an item for deletion.");
}
else
{
int i = Calls_lsb.SelectedIndex;
if (i > 0)
{
SqlConnection connection = new SqlConnection(//My Connection String);
string sqlStatement1 = "DELETE FROM Records WHERE CallID = #Id";
string sqlStatement2 = "DELETE FROM Calls WHERE CallID = #Id";
connection.Open();
SqlCommand cmd1 = new SqlCommand(sqlStatement1, connection);
cmd1.Parameters.AddWithValue("#Id", Calls_lsb.Items[i]);
cmd1.ExecuteNonQuery();
SqlCommand cmd2 = new SqlCommand(sqlStatement2, connection);
cmd2.Parameters.AddWithValue("#Id", Calls_lsb.Items[i]);
cmd2.ExecuteNonQuery();
connection.Close();
Calls_lsb.Items.Remove(Calls_lsb.Items[i]);
}
else
{
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
I get no exceptions and I have similar code that adds records that works fine. I tried stepping into the code but it all seemed fine. It simply just does not delete the row from the database. It removes the correct item from the list, just not the database.
If anyone could shine some light on this situation that would be great, thanks!
Edit : Ok, I seem to have fixed the problem. I just removed the whole i = selected index stuff and replace the 'Calls_lsb.Items[i]' with '(Calls_lsb.SelectedIndex + 1)'. I don't really understand why I was getting an exception when I tried to add 1 to i as this is basically doing the same thing.
Replace your below line code.
cmd1.Parameters.AddWithValue("#Id", Calls_lsb.Items[i]);
//with
cmd1.Parameters.AddWithValue("#Id", Calls_lsb.Items[i].Value);
and
cmd2.Parameters.AddWithValue("#Id", Calls_lsb.Items[i]);
// with
cmd2.Parameters.AddWithValue("#Id", Calls_lsb.Items[i].Value);

Categories

Resources