SQL Update statement on Winforms - c#

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();
}
}

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

Show data in Textboxes from database in C#

Is there anything wrong with my code? It is not showing data in textboxes. The same funtion is working for another table in database but not for this one.
private void metroButton1_Click(object sender, EventArgs e)
{
con = new SqlConnection(constr);
String query = "Select FROM Student WHERE Std_ID = '" + metroTextBox1.Text + "'";
cmd = new SqlCommand(query, con);
con.Open();
try
{
using (SqlDataReader read = cmd.ExecuteReader())
{
while (read.Read())
{
// metroTextBox1.Text = (read["ID"].ToString());
metroTextBox2.Text = (read["Name"].ToString());
metroTextBox3.Text = (read["F_Name"].ToString());
metroTextBox4.Text = (read["Std_Age"].ToString());
metroTextBox5.Text = (read["Address"].ToString());
metroTextBox6.Text = (read["Program"].ToString());
metroComboBox1.Text = (read["Course"].ToString());
}
}
}
finally
{
con.Close();
}
}
you need to give column names in the select statement or select *
for example :
String query = "Select * from Student WHERE Std_ID = '" + metroTextBox1.Text + "'";
Not related to Question: you can change the while loop to if condition if you have one record for given id. even there are many records for given id you will see the last record data only because of the while loop will overwrite the textboxes in every record.
Update :
There isn't anything wrong with Syntax because the same syntax is
working for modifying teacher funtion.
No, this is incorrect, remove the try catch in your code then you will see the exception of syntax error

C# edit button to Access database

I have a particular part of an inventory interface that requires an employee to select his or her name from a combo box and then scan a product to the table assigned to the name of the employee.
My curiosity is: When hitting the EDIT, ADD OR DELETE button it knows what table to perform this function in from a Switch - Case statement with that employee name on it. The problem is, the piece of code is long for each employee, especially for 9 employees that each have a Switch - Case statement.
Any advice on how to simplify this or shorten the code? I do understand in advance about the parameterized SQL that I am failing to use. Just trying to accomplish this first.
private void btnAdd_Click(object sender, EventArgs e)
{
ActiveControl = txtSerialN;
if (!string.IsNullOrEmpty(txtSerialN.Text) && !string.IsNullOrEmpty(cboEmpName.Text))
switch (cboEmpName.SelectedItem.ToString().Trim())
{
case "John Doe":
try
{
connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
command.CommandText = "INSERT INTO JohnDoe(SerialNumber,PartNumber,DateEntered,Customer) values ('" + txtSerialN.Text + "','" + txtPart.Text + "','" + txtDate.Text + "','" + txtCustomer.Text + "')";
command.ExecuteNonQuery();
MessageBox.Show("Inventory Added".PadLeft(23));
connection.Close();
txtSerialN.Clear();
txtPart.Clear();
txtDate.Clear();
txtCustomer.Clear();
command.CommandText = "SELECT * FROM JohnDoe ORDER BY PartNumber";
OleDbDataAdapter db = new OleDbDataAdapter(command);
DataTable dt = new DataTable();
db.Fill(dt);
dataGridEmpParts.DataSource = dt;
}
catch (OleDbException)
{
string strmsg = "THIS SERIAL NUMBER ALREADY EXISTS ! , Please try again";
MessageBox.Show(strmsg, "YOU CAN'T ENTER THE SAME ONE AGAIN", MessageBoxButtons.OK,
MessageBoxIcon.Exclamation,
MessageBoxDefaultButton.Button1);
connection.Close();
}
break;
}
}
I would rather put up a lookup table that will have columns such as EmployeeName, AssignedTable and dynamically construct the commandtext based on the parameter values.
I suspect this problem could more efficiently be fixed by altering the database. Perhaps even as simple as adding a field for employee name.

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.

MySql connection in C#

i was making a simple windows application form, to register some people in a database, so i made a connection class there is it:
public void Query_send(string cmd)
{
String config = "server=127.0.0.1;uid=root;database=bdcliente;";
MySqlConnection conn = new MySqlConnection(config);
MySqlCommand comm = new MySqlCommand(cmd, conn);
try
{
conn = new MySql.Data.MySqlClient.MySqlConnection();
conn.ConnectionString = config;
conn.Open();
}
catch
{
MessageBox.Show("Error when connecting to the database!");
}
finally
{
conn.Close();
}
}
and then in the BUTTON to give the informations for the MySql i use this:
private void button1_Click(object sender, EventArgs e)
{
Query instance = new Query();
instance.Query_send("INSERT INTO `tbcliente`(`codCliente`, `name`, `cpf`, `telephone`) VALUES ([" + textBox1 + "],[" + textBox2 + "],[" + textBox3 + "],[" + textBox4 + "])");
}
i always get the error with the connection when i click the register button, may someone help me or give me a link of a tutorial that teaches the correct way of doing this?
Thanks, Iago.
My guess is that you need to wrap the VALUES clause results in single quotes as the SQL you are generating will be invalid.
VALUES ('" + textbox1 + "')
Brackets are only required when referring to table or column names. Not when you're referring to string literals.
Odd question, but have you tried applying a password to the database? Depending on the version of MySQL, I have had some issues with leaving the root password unassigned (on local machine you can be safe and just assign 'root' as the password as well). Another option would be to create a user account with permissions and try connection with those credentials.
Not sure if that will help, but it's process of elimination.
Also not sure if method was work in process, but even if it connected there was no execute command against the database.
public void Query_send(string cmd)
{
String config = "server=localhost;uid=root;database=bdcliente;";
MySqlConnection conn = new MySqlConnection(config);
MySqlCommand comm = new MySqlCommand(cmd, conn);
try
{
conn.Open();
comm.ExecuteNonQuery(); '--this was missing
}
catch
{
MessageBox.Show("Error when connecting to the database!");
}
finally
{
conn.Close();
}
}

Categories

Resources