VB.NET 使用Nuget安装LiteDB轻量化数据库

VB.NET · 07-03 · 331 人浏览

如果对数据写入要求不高,需要轻量级的数据管理的话,推荐LiteDb数据库。
安装之后只有一个DLL文件来做调用。

相关代码片段:

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        ' 获取应用程序的目录
        Dim appDirectory As String = AppDomain.CurrentDomain.BaseDirectory
        ' 数据库文件路径
        Dim dbPath As String = Path.Combine(appDirectory, "example.db")

        ' 打开或创建数据库文件
        Using db As New LiteDatabase(dbPath)
            ' 获取Users集合
            Dim users = db.GetCollection(Of User)("Users")

            ' 创建索引
            users.EnsureIndex(Function(x) x.ID, True)

            ' 插入示例数据
            Dim user As New User With {.Name = "John Doe"}
            users.Insert(user)
            Dim results = users.FindAll().ToList()

            For Each u In results
                Console.WriteLine($"ID: {u.ID}, Name: {u.Name}")
            Next
        End Using

        Console.WriteLine("数据库和表已创建。")
        Console.ReadLine()
    End Sub

    Public Class User
        Public Property ID As Integer
        Public Property Name As String
    End Class

    Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
        ' 获取应用程序的目录
        Dim appDirectory As String = AppDomain.CurrentDomain.BaseDirectory
        ' 数据库文件路径
        Dim dbPath As String = Path.Combine(appDirectory, "example.db")

        ' 打开或创建数据库文件
        Using db As New LiteDatabase(dbPath)
            ' 获取Users集合
            Dim users = db.GetCollection(Of User)("Users")

            ' 创建索引
            users.EnsureIndex(Function(x) x.ID, True)

            ' 禁用自动索引更新
            users.EnsureIndex(Function(x) x.ID, False)

            ' 准备批量插入
            Dim batchSize As Integer = 100000
            Dim batch As New List(Of User)(batchSize)

            For i As Integer = 0 To 999999
                Dim user As New User With {.Name = $"User {i}"}
                batch.Add(user)

                If batch.Count >= batchSize Then
                    users.InsertBulk(batch)
                    batch.Clear()
                End If
            Next

            ' 插入剩余的数据
            If batch.Count > 0 Then
                users.InsertBulk(batch)
            End If
            Console.WriteLine(batch.Count)
            ' 重新启用自动索引更新
            users.EnsureIndex(Function(x) x.ID, True)
        End Using

        Console.WriteLine("从0到999999的用户已插入。")
    End Sub

图形化管理软件:

https://github.com/mbdavid/LiteDB.Studio/releases/tag/v1.0.3

* 人工审核评论,通过后即可正常显示。软件建议请添加微信