Source Codes
Source Codes

Reputation: 51

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);

Upvotes: 1

Views: 1398

Answers (2)

Soner Gönül
Soner Gönül

Reputation: 98750

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();
}

Upvotes: 0

Vanarajan
Vanarajan

Reputation: 979

You will need to provide a reference to

 System.Data.SqlServerCe (in system.data.sqlserverce.dll)

And replace

SqlConnection with SqlCeConnection

SqlCommand with SqlCeCommand

Upvotes: 1

Related Questions