Sheep
Sheep

Reputation: 49

Insert Into local database C#

I can't Insert and select from Local database data in C#.

I've read these articles

All the code samples are the same, here's my sample.

SqlCeConnection conn = new SqlCeConnection(@"Data Source=|DataDirectory|\PacjenciDB.sdf");
conn.Open();
SqlCeCommand cmd = conn.CreateCommand();

cmd.CommandText="INSERT INTO pacjenci (nazwiskoimie,adres,skierowany,opis) values (@nazwiskoimie,@adres,@skierowany,@opis)";
cmd.Parameters.AddWithValue("@nazwiskoimie", txtnazwiskoimie.Text);
cmd.Parameters.AddWithValue("@adres", txtadres.Text);
cmd.Parameters.AddWithValue("@skierowany", txtskierowany.Text);
cmd.Parameters.AddWithValue("@opis", txtopis.Text);

cmd.ExecuteNonQuery();

conn.Close();

Can someone tell me what I'm doing wrong?

I've tried tons of samples about insert data, but it doesn't work.

I can manage .MDF, but .SDF seems quite problematic.

Hope you help me

Upvotes: 0

Views: 3273

Answers (4)

ErikEJ
ErikEJ

Reputation: 41769

Look for a copy of the database with data in your bin/debug folder.

Solution is to not use |DataDirectory|, but use full path instead.

Upvotes: 1

martin
martin

Reputation: 299

Ok, I'm going to take a guess here. Is the PacjenciDB.sdf included into Visual Studio project by any chance? Do you have the property "Copy to output folder" set to "Always" or something similar? It seems that every time you do a build you could be overwriting your output folder database file. Try putting the database in a folder that is not inside VS project.

BTW, your code is OK.

Upvotes: 1

user2316116
user2316116

Reputation: 6814

The above code is correct and most likely the problem is somewhere else, where you call that code from. If there is a problem with db connection or data is wrong - you should get an exception. Since there is no error occurred and no new records added - the code is not executed at all.

P.S.

.sdf is a Sql Server Compact Local Database, so using System.Data.SqlServerCe is correct http://msdn.microsoft.com/en-us/library/system.data.sqlserverce(v=vs.100).aspx

Upvotes: 0

Jon Hunter
Jon Hunter

Reputation: 880

Try using double backslash when setting the path to your database file:

string dbPath + "Data Source=C:\\DataDirectory\\PacjenciDB.sdf";
SqlCeConnection conn = new SqlCeConnection(dbPath);
conn.Open();
SqlCeCommand cmd = conn.CreateCommand();

cmd.CommandText="INSERT INTO pacjenci (nazwiskoimie,adres,skierowany,opis) values (@nazwiskoimie,@adres,@skierowany,@opis)";
cmd.Parameters.AddWithValue("@nazwiskoimie", txtnazwiskoimie.Text);
cmd.Parameters.AddWithValue("@adres", txtadres.Text);
cmd.Parameters.AddWithValue("@skierowany", txtskierowany.Text);
cmd.Parameters.AddWithValue("@opis", txtopis.Text);

cmd.ExecuteNonQuery();

conn.Close();

Upvotes: -1

Related Questions