Insert Into local database C#

狂风中的少年 提交于 2019-12-12 01:25:27

问题


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

I've read these articles

  • C# - Writing data in local database
  • http://msdn.microsoft.com/en-us/library/system.data.sqlserverce.sqlceconnection(v=vs.100).aspx
  • How to add local database items into textBox using listBox in C#

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


回答1:


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.




回答2:


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.




回答3:


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




回答4:


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


来源:https://stackoverflow.com/questions/24104947/insert-into-local-database-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!