Search code examples
c#sqlsql-servervisual-studio-2010sql-server-ce

How to save data to local database in visual studio 2010?


I know to add data to a SQL Server database but don't know to add data to local database that have .sdf extension in Visual Studio 2010, please give me code example to add data to local database through C#.

string cb = "Insert into tblFees(Salutation,Name) VALUES (@d1,@d2)";  //id  li

cmd = new SqlCommand(cb);
cmd.Connection = con;
cmd.Parameters.AddWithValue("@d1", cmbSalutation.Text);
cmd.Parameters.AddWithValue("@d2", tbName.Text);                

cmd.ExecuteReader();

MessageBox.Show("Successfully saved", "Patient Details", MessageBoxButtons.OK, MessageBoxIcon.Information);

Solution

  • ExecuteReader returns data for your query. You need to use ExecuteNonQuery instead since you are not return any data, you just insert it.

    Use using statement to dispose your connection and command automatically by the way.

    And do not use AddWithValue method. It may generate unexpected and surprising results sometimes. Use Add method overloads to specify your parameter type and it's size.

    using(var con = new SqlConnection(conString))
    using(var cmd = con.CreateCommand())
    {
       cmd.CommandText = "Insert into tblFees(Salutation,Name) VALUES (@d1,@d2)";
       cmd.Parameters.Add("@d1", SqlDbType.NVarChar).Value = cmbSalutation.Text;
       cmd.Parameters.Add("@d2", SqlDbType.NVarChar).Value = tbName.Text;
    
       con.Open();
       cmd.ExecuteNonQuery();
    }