Using a database in .NET

前端 未结 3 1664
终归单人心
终归单人心 2021-01-21 10:48

UPDATED QUESTION:

Ok, I am going to simplify my question since I don\'t really know how to answer your questions.

Say I create a new Windows Forms Application, t

3条回答
  •  一生所求
    2021-01-21 11:15

    Really hard to understand what is going on without seeing your code, but I will make some guesses:

    Say I create a new Windows Forms application then Project->Add New Item->Local Database

    This will create an empty SQL Server Compact Edition .SDF file in your project. You can edit this file from Visual Studio or SQL CE Query Analyzer.

    Then in Database Explorer I create a table ("testtable") and give it an "ID" column and "VALUE" column.

    This will create an empty table in your .SDF file. Those are pretty bad names, but for test purpose we can use them.

    Can you provide me with the steps to simply add a row to the database from the code?

    System.Data.SqlServerCe provides methods to manage .SDF files. To add a row to your test table:

    using (SqlCeConnection myConnection = new SqlCeConnection(@"Data Source=Path\To\Your\SDF\file.sdf;"))
    using (SqlCeCommand myCmd = myConnection.CreateCommand())
    {
        myCmd.CommandType = CommandType.Text;
        myCmd.CommandText = "INSERT INTO testtable (ID, [VALUE]) VALUES (1, whatever)";
        myConnection.Open();
        myCmd.ExecuteNonQuery();
    }

    Be aware that Path\To\Your\SDF\file.sdf may not be what your think; Visual Studio by default copies project files to the Project Build Output Path (e.g. Path\to\your\project\bin\Debug\file.sdf). If you change the built file then rebuild your project, the original .SDF file gets recopied to your output path, wiping out any changes you have made to your project file. If that's not what you want you will have to explain what you are trying to accomplish.

    For example, to make changes apply only to the built project file, change your data file "Copy to Output Directory" property in VS to "Copy if Newer".

提交回复
热议问题