C# SQL Server CE not inserting

僤鯓⒐⒋嵵緔 提交于 2019-12-10 12:31:31

问题


SqlCeConnection sqlCnn = 
    new SqlCeConnection(Properties.Settings.Default.mainDBConnectionString);

SqlCeCommand sqlCmd = new SqlCeCommand(
    "INSERT INTO desktopItems (Location,Label) VALUES (@Location, @Label)", 
    sqlCnn);

sqlCnn.Open();
sqlCmd.Parameters.Add("@Location", openExe.FileName.ToString());
sqlCmd.Parameters.Add("@Label", openExe.SafeFileName.ToString());
sqlCmd.ExecuteNonQuery();

sqlCnn.Close();

I have this code but when I run the program, the database is not updating ...


回答1:


Usually this scenario is caused by a simple error in visualizing the database.
Your INSERT works as expected, but you check if the insert succeded looking at a database in the wrong directory.

Using the DATADIRECTORY substitution string with a WinForms application means that, at debug time, your database is expected to be located in the directory BIN\DEBUG from your base project folder.
Visual Studio make sure that this is the case because in your project, the database file, is marked with the property Copy To The Output Directory set to Copy Always or Copy If Newer.

And it is here that the insert happens when you run your code inside a debug session of Visual Studio.

Then you check the result of the execution using the SERVER EXPLORER connection. But this connection points to the original database in the Project Folder and, of course, the new record is not present.

Usually the database in the project folder is kept up to date for the deployement, with the correct schema and initial data, but without any records that are inserted just for debug purpose.

So you could simply add a new connection to the SERVER EXPLORER pointing to the database in the BIN\DEBUG, rename it (like 'DEBUG-DB') and keep your original connection in case you need to change something in the schema of the database before releasing your application.



来源:https://stackoverflow.com/questions/19887992/c-sharp-sql-server-ce-not-inserting

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