Cannot insert data into Local Database in WPF

后端 未结 2 1898
北荒
北荒 2021-01-20 14:37

In a project, I have a local database, (I am using the datagrid to view the data), but the problem is that when I insert into database using the insertion query, the inserti

相关标签:
2条回答
  • 2021-01-20 15:22

    In what folder is your application running? If it is in the Program Files tree you likely do not have write permissions to the sdf file (especially on Windows 7 unless you have turned off UAC or are elevating your app prior to execution).

    Even if that is not your short term issue I would recommend finding a different place for the sdf file, such as one of the AppData locations. Expecting to be able to write to your install location is not a guaruntee and depends on how and where your app is deployed.

    0 讨论(0)
  • 2021-01-20 15:26
    1. Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) + "\\MyDatabase.sdf" is the path to your application folder. Depending on installation options your file may not be installed there. Use a connection string of "DataSource=|DataDirectory|\\MyDatabase.sdf;..." as described here.

    2. Even if your data is actually stored there, depending on user permissions the user may not be able to write to that directory. Also, when the user uninstalls or updates your app, his data will be deleted. People don't like that. You should copy the data to a user-writable folder; the earlier link shows how to do that as well.

    3. If you have a Visual Studio project with a database a part of your project, it will probably have the "Copy to Output Directory" property set to "Copy". That means each time you run in the debugger you get a brand-new database copied from your source project, overwriting whatever was there before. Any changes will be in this temporary output folder, not in your original source data. When you debug the app again, the temporary copy is deleted. Further explanation in this answer.

    0 讨论(0)
提交回复
热议问题