C#/sql changing sql parameter with swl parameter - c#

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)

Related

Update statement does nothing

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

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# mysql - add the value of stock and new entries when the description is the same

Sorry guys to my english..
when i insert a record the same description with the existing record in datagridview but different quantity.. it creates a new row for the last record i inserted...
what i want is to ADD the quantity i inserted to the old record with the same description..
1. HERE'S THE IMAGE FOR YOU TO UNDERSTAND THE PROBLEM
2. THIS IS WHAT HAPPEN
The result should be QUANTITY = 25.. and also the totalcbm.. totalcbm = quantity * cbm
private void btnSave_Click(object sender, EventArgs e)
{
MySqlConnection connection = new MySqlConnection(MyConnectionString);
MySqlCommand cmd;
connection.Open();
try
{
cmd = connection.CreateCommand();
cmd.CommandText = "INSERT INTO Inventory(Quantity,Unit,ItemCode,ItemName,Cbm,TotalCbm)VALUES(#Quantity,#Unit,#ItemCode,#ItemName,#Cbm,#TotalCbm)";
cmd.Parameters.AddWithValue("#Quantity", tbQuantity.Text.ToString());
cmd.Parameters.AddWithValue("#Unit", tbUnit.Text.ToString());
cmd.Parameters.AddWithValue("#ItemCode", tbItemCode.Text.ToString());
cmd.Parameters.AddWithValue("#ItemName", tbItemName.Text.ToString());
cmd.Parameters.AddWithValue("#Cbm", tbCbm.Text.ToString());
cmd.Parameters.AddWithValue("#TotalCbm", tbTotalCbm.Text.ToString());
cmd.ExecuteNonQuery();
}
catch (Exception)
{
throw;
}
finally
{
if (connection.State == ConnectionState.Open)
{
connection.Close();
frmUserAE form1 = new frmUserAE();
AccountForm.LoadGrid();
this.Hide();
}
}
}
You are doing an INSERT statement, which will create a new row.
You should do an UPDATE statement, depending on what you think is your primary key (the description?).

OleDbException was unhandled by user code in c#

Here is the cs file:
public int CheckExisting(String sqlDbQry, String sTable)
{
Qry = sqlDbQry;
con = new OleDbConnection(connectionstr);
if (con.State == ConnectionState.Open)
con.Close();
con.Open();
cmd = new OleDbCommand(Qry, con);
dr = cmd.ExecuteReader();
while (dr.Read())
rQry = Convert.ToInt32(dr[0].ToString());
con.Close();
return rQry;
}
Here is my another cs:
protected void btnsub_Click(object sender, EventArgs e)
{
if (objAdmin.CheckExisting("SELECT COUNT(*) FROM registration where Email='" + Textemail.Text.Trim() + "'", "Temp") > 0)
{
lblmail.Text = "Your EmailId already Registered, Please Login!";
return;
}
if (objAdmin.CheckExisting("SELECT COUNT(*) FROM registration where Phone_num='" + Textphone.Text.Trim() + "'", "Temp") > 0)
{
lblmail.Text = "Mobile number already exists, Please Login!";
return;
}
}
When i enter input details and hit submit, it shows error something like this,
Here is the error of Screenshot
Can anyone help me to fix this?
You are manually building a sql string from a textbox labeled "email". Email addresses usually contain an "#". Because you are building a raw sql query you are putting the "#" directly in to the query. OleDb interprets that as a SQL parameter, and expects you to supply it, which you are not, which is what is causing the error. You will get a similar error if any of your text boxes contain a ' (single quote).
You should look in to using OleDbCommand and OleDbParameter to pass in your parameters instead of sending raw strings. This will also fix your sql injection attack vulnerability that others have mentioned.
I can't edit your post so I'm doing it here.
public int CheckExisting(String sqlDbQry, String sTable)
{
try
{
Qry = sqlDbQry;
con = new OleDbConnection(connectionstr);
if (con.State == ConnectionState.Open)
con.Close();
con.Open();
cmd = new OleDbCommand(Qry, con);
dr = cmd.ExecuteReader();
while (dr.Read())
rQry = Convert.ToInt32(dr[0].ToString());
con.Close();
return rQry;
}
catch (OleDbException ex)
{
string message = ex;
//put your message on a texbox or alert handler error on the web
//or while debugging use a breakpoint on the exception handler
//use log
Console.WriteLine(message);
}
}
Keep in mind that with OleDb, parameters are positional, not named. You can name your parameters, but you cannot use the # syntax in your command (it throws an error about needing to declare a scalar variable) ... the correct syntax is to use the ? ... and it will take the parameters in the order in which you've added them.
Also, I prefer the .AddWithValue syntax, which is even more readable, I think.
protected void btnsub_Click(object sender, EventArgs e)
{
if (objAdmin.CheckExisting("SELECT COUNT(*) FROM registration where Email='" + this.Textemail.Text.Trim() + "'", "Temp") > 0)
{
lblmail.Text = "Your EmailId already Registered, Please Login!";
return;
}
if (objAdmin.CheckExisting("SELECT COUNT(*) FROM registration where Phone_num='" + this.Textphone.Text.Trim() + "'", "Temp") > 0)
{
lblmail.Text = "Mobile number already exists, Please Login!";
return;
}
}
Just put this.Textemail.Text and this.Textphone.Text , i hope so it will be helpful for you.

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