.NET Window Forms local database

2020-04-19 05:22发布

I just started writing a Windows Forms Application and I'd like to store data in a Database but not in an actual DB Server.. something like SQLite (local, server independent).

Does .NET have anything like this out of the box? I looked into DataSets but I'm have a hard time populating it.

Any pointers are appreciated, thanks!

3条回答
Evening l夕情丶
2楼-- · 2020-04-19 06:01

Consider Sql Server Compact edition, you can find instruction how to add it to your project here. Below sample code to retrieve data from the table MyTable containing column Id in database file MyDb.sdf, you also need to add System.Data.SqlServerCe assembly reference and namespace System.Data.SqlServerCe

using (SqlCeConnection ceConn = new SqlCeConnection(@"Data Source=|DataDirectory|\MyDb.sdf"))
using (SqlCeCommand ceCmd = new SqlCeCommand("select Id from MyTable", ceConn))
{
    ceConn.Open();
    SqlCeDataReader dataR = ceCmd.ExecuteReader();
    while (dataR.Read())
    {
        Console.WriteLine(dataR["Id"].ToString());
    }
}
查看更多
神经病院院长
3楼-- · 2020-04-19 06:10

If you don't have to save a huge amount of data you can use XML or even JSON. With JSON.NET you can serialize objects and write them to a text file, then read json file and get your data back.

// define you data type
class MyData
{
   ...
}

// using MyData
string jsonString= myDaJsonConvert.SerializeObject<List<Profile>>(data);
List<Profile> data = myDaJsonConvert.DeserializeObject<List<Profile>>(jsonString);

EDIT 1:

Even if its System.Data.SQlite assembly is outdated this legacy setup file contains a "Designer" component for ADO.NET 2.0 which might simplify a lot the Dataset creation routine. Please remember to update SQlite libraries from this site later.

查看更多
聊天终结者
4楼-- · 2020-04-19 06:14

You can try SQL Server Compact, i didn't used it, but it seems that it is what you are looking for.

查看更多
登录 后发表回答