I am working on an app and I got stuck in this problem. I am trying to add a record to my SQL local database. It gives the successful message box but when I close the app and check the table the record is not there. I tried adding it in two different ways and none of them worked. I will post the code here
Here is the first method that I tried
using (SqlConnection _conn = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\Restaurant.mdf;Integrated Security=True"))
{
using (SqlCommand _cmd = new SqlCommand("INSERT INTO Chelneri(username, nume, prenume, email, parola) values ('" + textBoxUser.Text.ToString().Trim() +"', '"+ textBoxNume.Text.ToString().Trim() +"', '"+ textBoxPrenume.Text.ToString().Trim() +"', '"+ textBoxEmail.Text.ToString().Trim() +"', '"+ textBoxParola.Text.ToString().Trim() +"')", _conn))
{
try
{
_conn.Open();
_cmd.ExecuteNonQuery();
_conn.Close();
textBoxUser.Text = string.Empty;
textBoxNume.Text = string.Empty;
textBoxPrenume.Text = string.Empty;
textBoxParola.Text = string.Empty;
textBoxEmail.Text = string.Empty;
MessageBox.Show("Utilizatorul a fost creat!", "Restaurant Casa Verde", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch(Exception ex)
{
MessageBox.Show(ex.ToString(), "Restaurant Casa Verde", MessageBoxButtons.OK, MessageBoxIcon.Error);
_conn.Close();
}
}
}
And here is the second one.
using (SqlConnection _conn = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\Restaurant.mdf;Integrated Security=True"))
{
using (SqlCommand _cmd = new SqlCommand("INSERT INTO Chelneri(username, nume, prenume, email, parola) values (@user, @nume, @prenume, @email, @parola)", _conn))
{
try
{
_conn.Open();
_cmd.Parameters.Clear();
_cmd.Parameters.Add("@user", SqlDbType.NVarChar).Value = textBoxUser.Text.ToString().Trim();
_cmd.Parameters.Add("@email", SqlDbType.NVarChar).Value = textBoxEmail.Text.ToString().Trim();
_cmd.Parameters.Add("@nume", SqlDbType.NVarChar).Value = textBoxNume.Text.ToString().Trim();
_cmd.Parameters.Add("@prenume", SqlDbType.NVarChar).Value = textBoxPrenume.Text.ToString().Trim();
_cmd.Parameters.Add("@parola", SqlDbType.NVarChar).Value = textBoxParola.Text.ToString().Trim();
_cmd.ExecuteNonQuery();
_conn.Close();
textBoxUser.Text = string.Empty;
textBoxNume.Text = string.Empty;
textBoxPrenume.Text = string.Empty;
textBoxParola.Text = string.Empty;
textBoxEmail.Text = string.Empty;
MessageBox.Show("Utilizatorul a fost creat!", "Restaurant Casa Verde", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch(Exception ex)
{
MessageBox.Show(ex.ToString(), "Restaurant Casa Verde", MessageBoxButtons.OK, MessageBoxIcon.Error);
_conn.Close();
}
}
}
I don't think the code is the problem. I think that I am missing something and I don't know what.
Here is a printscreen of the database.