Show status when data in database MySQL was deleted in C# - c#

I have issue when showing the status when data was delete or not. Here's the code
public bool isDelete (String nim, String pass)
{
String query = "delete from dbmahasiswa where NIM=#NIM AND Password=#Password";
class_Mahasiswa cm = new class_Mahasiswa();
try
{
connect.Open();
MySqlCommand cmd = new MySqlCommand(query, connect);
cmd.Parameters.AddWithValue("#NIM", nim);
cmd.Parameters.AddWithValue("#Password", pass);
cmd.ExecuteNonQuery();
MySqlDataReader reader;
reader = cmd.ExecuteReader();
int count = 0;
while (reader.Read())
{
count += 1;
}
if (count == 1)
{
System.Windows.Forms.MessageBox.Show("sukses!", "Status");
return true;
}
else
System.Windows.Forms.MessageBox.Show("akun tidak ditemukan", "Status");
return false;
connect.Close();
}
catch (Exception e)
{
System.Windows.Forms.MessageBox.Show(e.Message, "Warning");
return false;
}
return true;
}
If I type the wrong username or password, it will show MessageBox "akun tidak ditemukan"(account not found). Also when I type the right username and password to delete it, it will show that MessageBox because the function will read the database after data has been deleted.
My question is, how to show the "Sukses" MessageBox when data has been deleted?

You are calling ExecuteReader. The ExecuteReader is used to read data returning from the query with a SELECT statement. You can't use it to know if a row or more has been deleted. For this task you use just ExecuteNonQuery and get the return value to know the number of rows 'affected' by the query command
String query = "delete from dbmahasiswa where NIM=#NIM AND Password=#Password";
class_Mahasiswa cm = new class_Mahasiswa();
try
{
connect.Open();
MySqlCommand cmd = new MySqlCommand(query, connect);
cmd.Parameters.AddWithValue("#NIM", nim);
cmd.Parameters.AddWithValue("#Password", pass);
int rows = cmd.ExecuteNonQuery();
if (rows > 0)
{
System.Windows.Forms.MessageBox.Show("sukses!", "Status");
return true;
}
else
{
System.Windows.Forms.MessageBox.Show("akun tidak ditemukan", "Status");
return false;
}
}
catch (Exception e)
{
System.Windows.Forms.MessageBox.Show(e.Message, "Warning");
return false;
}
finally
{
connect.Close();
}
}
Also, it seems that you are using a global connect object for your connection. This is usually the source of many bugs like the one you have in your catch clause. If your code results in an exception you forgot to close the connection and, in the next call to connect.Open, you will get an error. I have added a finally to ensure proper closure of your connection object. However it is a better practice to keep the connection local to the code where you need it, open inside a using statement block to have it closed and disposed at the end of the block

Related

C# - Microsoft sql database | Can't add new user on my e-contact app

I tried to make an e-contact app with C# on Visual Studio 2019 connected to a Miscrosoft SQL database (local) following a youtube tutorial.
The app is not complete yet, anyway the btnAdd should work, but it doesn't add the user and the return of the method (Insert).
It always returns false - Can anyone help me?
private void BntAdd_Click(object sender, EventArgs e) {
//Get the value from the imput fields
c.Nome = txtBoxName.Text;
c.Cognome = txtBoxSurname.Text;
c.Telefono1= txtBoxPhone1.Text;
c.Telefono = txtBoxPhone.Text;
c.Email = txtBoxEmail.Text;
//Inserting Data into Database uing the method we created is previous episode
bool success = c.Insert(c);
if (success == true)
{
//Successfully Inserted
MessageBox.Show("New contact added!");
//Call the clear Method Here
Clear();
}
else
{
//Failed to add Contact
MessageBox.Show("ERROR!)");
}
//load Data on Data GRidview
DataTable dt = c.Select();
dgvRubrica.DataSource = dt;
}
public void Clear()
{
txtBoxName.Text = "";
txtBoxSurname.Text = "";
txtBoxPhone1.Text = "";
txtBoxPhone.Text = "";
txtBoxEmail.Text = "";
}
public bool Insert (rubricaClass c) {
bool isSuccess = false;
SqlConnection conn = new SqlConnection(myconnstrng);
try
{
string sql = "INSERT INTO tbl_Rubrica (Nome, Cognome, Telefono1, Telefono, Email) VALUES (#Nome, #Cognome, #Telefono1, #Telefono, #Email)";
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.Parameters.AddWithValue("#Nome", c.Nome);
cmd.Parameters.AddWithValue("#Cognome", c.Cognome);
cmd.Parameters.AddWithValue("#Telefono1", c.Telefono1);
cmd.Parameters.AddWithValue("#Telefono", c.Telefono);
cmd.Parameters.AddWithValue("#Email", c.Email);
conn.Open();
int rows = cmd.ExecuteNonQuery();
if (rows > 0)
{
isSuccess = true;
}
else
{
isSuccess = false;
}
}
catch (Exception ex)
{
}
finally
{
conn.Close();
}
return isSuccess;
}
It doesn't give any errors, it work but when i type the ata into txtBoxes and then i press the add button it says Error (message box inserte in the else)
Step 1 is to remove the catch-all exception handling from the Insert method. Most of the ADO.NET database classes implement IDisposable, so you just need a using(...) block to make sure the command is disposed automatically (which will also close and dispose the connection instance):
public bool Insert (rubricaClass c)
{
bool isSuccess = false;
SqlConnection conn = new SqlConnection(myconnstrng);
string sql = "INSERT INTO tbl_Rubrica (Nome, Cognome, Telefono1, Telefono, Email) VALUES (#Nome, #Cognome, #Telefono1, #Telefono, #Email)";
using(SqlCommand cmd = new SqlCommand(sql, conn))
{
cmd.Parameters.AddWithValue("#Nome", c.Nome);
cmd.Parameters.AddWithValue("#Cognome", c.Cognome);
cmd.Parameters.AddWithValue("#Telefono1", c.Telefono1);
cmd.Parameters.AddWithValue("#Telefono", c.Telefono);
cmd.Parameters.AddWithValue("#Email", c.Email);
conn.Open();
int rows = cmd.ExecuteNonQuery();
if (rows > 0)
{
isSuccess = true;
}
else
{
isSuccess = false;
}
}
return isSuccess;
}
Once that's squared away, Step 2 is to move your exception handling into the application. I don't recommend this "catch everything"-style code, but it works for now, I suppose:
private void BntAdd_Click(object sender, EventArgs e)
{
//Get the value from the imput fields
c.Nome = txtBoxName.Text;
c.Cognome = txtBoxSurname.Text;
c.Telefono1= txtBoxPhone1.Text;
c.Telefono = txtBoxPhone.Text;
c.Email = txtBoxEmail.Text;
try
{
//Inserting Data into Database uing the method we created is previous episode
bool success = c.Insert(c);
if (success == true)
{
//Successfully Inserted
MessageBox.Show("New contact added!");
//Call the clear Method Here
Clear();
}
else
{
//Failed to add Contact
MessageBox.Show("ERROR!)");
}
//load Data on Data GRidview
DataTable dt = c.Select();
dgvRubrica.DataSource = dt;
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
This will likely tell you that you either have an error in your SQL syntax, or that the command itself could not be run (i.e. the connection string is invalid or the server can't be reached).

Check on the result of an update is failing

Every time I click on change password it will change the password but it prompts the invalid combination
Here is my code
using (SqlCommand cmd = new SqlCommand("UPDATE LoginReport SET PassLogin = #NewPassLogin WHERE UserLogin = #UserLogin AND PassLogin = #PassLogin ", conn))
{
conn.Open();
cmd.Parameters.AddWithValue("#UserLogin", txtUser.Text);
cmd.Parameters.AddWithValue("#PassLogin", txtOldPass.Text);
cmd.Parameters.AddWithValue("#NewPassLogin", txtNewPass.Text);
SqlDataReader Dr = cmd.ExecuteReader();
if (Dr.HasRows == true)
{
MessageBox.Show("Sucessfully Updated Account");
}
else
{
MessageBox.Show("Invalid Combination");
}
}
Why is the check failing?
An update does not return any rows, a select does. Hence, HasRows is false.
You have to check another way if the update was succesful: by checking the result of ExecuteNonQuery(). It will return the rows affected. If that is more than 0, it was successful.
if (cmd.ExecuteNonQuery() > 0)
{
MessageBox.Show("Sucessfully Updated Account");
}
else
{
MessageBox.Show("Invalid Combination");
}
Instead of cmd.ExecuteReader(); you have to use cmd.ExecuteNonQuery(); which returns the number of affected rows.
int RowsAffected = cmd.ExecuteNonQuery();
if (RowsAffected == 1)
{
MessageBox.Show("Sucessfully Updated Account");
}
else
{
MessageBox.Show("Invalid Combination");
}
An Update Command does not return any rows so it's correct that Dr.HasRows == true returns false.
You should have to use ExecuteNonQuery.
ExecuteNonQuery: Use this operation to execute any arbitrary SQL statements in SQL Server if you do not want any result set to be returned.

Having troubles with a command's execution

So, basically what I'm doing is, after adding a diagnosis on the TextBox I'm checking if there is a Diagnosis with the same name already. The connection works fine, however, I'm having difficulties with executing the command in this line here:
var count = (int)cmd.ExecuteNonQuery();
Here's the full method
protected void MesmoDiagnostico_ServerValidate(object source, ServerValidateEventArgs args)
{
string connectionString = ConfigurationManager.ConnectionStrings["BDClinica"].ConnectionString;
SqlConnection connection = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand("Select COUNT(*) from Diagnosticos Where Diagnostico_Nome=#Diagnostico_Nome", connection);
connection.Open();
cmd.Parameters.AddWithValue("#Diagnostico_Nome", source);
var count = (int)cmd.ExecuteNonQuery();
if (count > 0)
{
args.IsValid = false;
}
else
{
args.IsValid = true;
}
connection.Close();
}
Am I missing something? Thanks!
According to MSDN, ExecuteNonQuery is for executing catalog or UPDATE/INSERT/DELETE operations and returns the number of rows affected. By using a COUNT, you're still looking for "number of rows" but it's being executed as query, not an update.
Since you only want one piece of data, technically the first column of the first row, you can use ExecutScalar instead.
This is almost the exact code that you need :
SqlConnection con = new SqlConnection(Settings.Default.FrakoConnectionString);
SqlCommand maxcommand = new SqlCommand("SELECT MAX(Counter) AS max FROM ppartikulieren", con);
try
{
con.Open();
max = (int)maxcommand.ExecuteScalar() + 1;
}
catch (Exception ex)
{
MessageBox.Show("Fout bij het plakken:\n" + ex.Message, "Frako planner", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
finally
{
con.Close();
}
you can also use a using statement of course. But the point is that you really need to cast the output of ExecuteScalar.

query shows data exists in the table in the sql server but it shows no row affected and return false always

I'm checking if a name already exists in the database. When I execute the query in the sql server it shows data but in application, it shows, no rows affected and it always returns false.
Here is my code:
string productExtentionName = productExtensionEntryTextBox.Text;
bool doesProductNameExtentionExist = false;
doesProductNameExtentionExist = _aProductEntryManager.DoesProductNameAlreadyExist(productExtentionName);
_aProduct.ProductNameExtention = productExtentionName;
if (doesProductNameExtentionExist != true)
{
if (!string.IsNullOrEmpty(_aProduct.ProductNameExtention))
{
saveNewProduct = _aProductEntryManager.SaveProductNameExtention(_aProduct);
if (saveNewProduct)
{
MessageBox.Show("Product name extention saved successful");
}
else
{
MessageBox.Show("Error saving product name extention");
}
}
else
{
MessageBox.Show("Please enter a product specication/extention");
}
}
else
{
MessageBox.Show("Product name extention / specification already exists");
}
Here is my Gateway
public bool DoesProductNameAlreadyExist(string productExtentionName)
{
_connection.Open();
string query = string.Format("SELECT ProductNameExtention FROM ProductNameExtentionEntryTable WHERE ProductNameExtention='{0}'", productExtentionName);
_command = new SqlCommand(query, _connection);
int affectedRows = _command.ExecuteNonQuery();
_connection.Close();
if (affectedRows > 0)
{
return true;
}
return false;
}
int affectedRows = _command.ExecuteNonQuery();
this will return -1;
Execute the query onto a SqlDataReader and check if it has rows.
Dont forget to close the reader.
SqlDataReader reader = _command.ExecuteReader();
if (reader.HasRows) MessageBox.Show("Yes"); else MessageBox.Show("No");
reader.Close();
try this
_command = new SqlCommand(query, _connection);
da.SelectCommand = _command ;
DataSet ds = new DataSet();
da.Fill(ds);
if (ds.Tables[0] != null)
{
if (ds.Tables[0].Rows.Count > 0)
{
//write your code
return true;
}
}
Use execute scalar instead of execute non query, as this is a select query and select query does not returns the no of rows affected, which is returned by the execute non-query.
so, in this case it's returning the default value 0, hence your method is returning false.
Also, you can modify query to use top 1 1, as here you are only checking if the product exists.
SELECT TOP 1 1 FROM ProductNameExtentionEntryTable WHERE ProductNameExtention=#productExtentionName

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