I am just a beginner trying to do my due diligence and research things properly. I am trying to go about the correct way of adding data into a database. I have read articles on the following:
- Not showing ConnectionString in plaintext. I currently store it in App.Config and I am still trying to figure out how to encrypt it.
usingkeyword to deal with disposable items.catch try finallyto deal with exceptions.- parameterized SQL statements to deal with SQL Injection.
I am looking for any advise to make my code better. I have revised it several times taking into account all the articles I have read about the topics above.
private void Btn_InsertData_Click(object sender, EventArgs e)
{
if (TextboxesAreNullorEmpty() == true)
{
MessageBox.Show("Please fill out all fields!");
return;
}
else
{
try
{
using (MySqlConnection conn = new MySqlConnection(Properties.Settings.Default.MySQLDBConnection))
using (MySqlCommand cmd = new MySqlCommand())
{
conn.Open();
cmd.Connection = conn;
cmd.CommandText = "INSERT INTO `sites` (`ContractNumber`, `SiteName`, `SitePhoneNumber`, `SiteAddLine1`, `SiteAddLine2`, `SiteAddCity`, `SiteAddCounty`, `SiteAddPostcode`, `SiteAddCountry`) VALUES (@contract_name, @site_name, @site_phone_number, @site_add_line1, @site_add_line2, @site_add_city, @site_add_county, @site_add_postcode, @site_add_country)";
cmd.Prepare();
cmd.Parameters.AddWithValue("@contract_name", this.txtBox_ContractNumber.Text);
cmd.Parameters.AddWithValue("@site_name", this.txtBox_SiteName.Text);
cmd.Parameters.AddWithValue("@site_phone_number", this.txtBox_SitePhoneNumber.Text);
cmd.Parameters.AddWithValue("@site_add_line1", this.txtBox_SiteAddLine1.Text);
cmd.Parameters.AddWithValue("@site_add_line2", this.txtBox_SiteAddLine2.Text);
cmd.Parameters.AddWithValue("@site_add_city", this.txtBox_SiteAddCity.Text);
cmd.Parameters.AddWithValue("@site_add_county", this.txtBox_SiteAddCounty.Text);
cmd.Parameters.AddWithValue("@site_add_postcode", this.txtBox_SiteAddPostcode.Text);
cmd.Parameters.AddWithValue("@site_add_country", this.txtBox_SiteAddCountry.Text);
cmd.ExecuteNonQuery();
MessageBox.Show("Site Details Added");
}
}
catch (Exception ex)
{
MessageBox.Show(string.Format("An error occurred {0}", ex.Message), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally
{
ClearAllTextBoxes();
}
}
}
private void Btn_InsertData_Click... where is this code actually going to be running? \$\endgroup\$INSERTfailed, doesn't it? \$\endgroup\$