0

I attached the service-based database to my windows application and I used the following code to save the data, it is working correctly, but when I close the application and open again the data which I saved was cleared automatically.

How to save the data permanently...

string c = Application.StartupPath + "\\Stock.mdf";
SqlConnection con = new SqlConnection(@"AttachDbFilename='"+c+"';Integrated Security=True;Connect Timeout=30;User Instance=True");

con.Open();

SqlCommand cmd = new SqlCommand("Insert into Codedetails values('TF','" + txt_productcode.Text + "','" + txt_productname.Text + "','" + txt_brandcode.Text + "','" + txt_brandname.Text + "')", con);
cmd.ExecuteNonQuery();
con.Close();
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Guna Sundari
  • 35
  • 1
  • 8

1 Answers1

1

first, it is better to use init catalog instead attached file (common practice) secondly use using to dispose your ressources thirdly, it is better to do your sql query in a stored procedure which take parameters (sql in database and C# in vs2010 ;-)

string c = Application.StartupPath + "\\Stock.mdf";
string connectionString = @"AttachDbFilename='"+c+"';Integrated Security=True;Connect Timeout=30;User Instance=True";
using (SqlConnection connection = new SqlConnection(connectionString))
    {
        con.Open();
        using (SqlCommand command = new SqlCommand(Insert into Codedetails values('TF','@productcode','@productname','@brandcode','@brandname'), con))
            {       
        command.Parameters.Add(new SqlParameter("productcode", txt_productcode.Text));
        command.Parameters.Add(new SqlParameter("productname", txt_productcode.Text));
        command.Parameters.Add(new SqlParameter("brandcode", txt_brandcode.Text));
        command.Parameters.Add(new SqlParameter("brandname", txt_brandname.Text));
        command.ExecuteNonQuery();
        }
    }
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Hassan Boutougha
  • 3,871
  • 1
  • 17
  • 17
  • hi Hassan Boutougha, thanks for replying me...my datas are saved well, my problem is i added the database within the application, if i close the application, all the datas are deleted, i want the data should be present – Guna Sundari Sep 29 '12 at 07:48