0

我只是想确保这是使用 SQLite 以获得最快性能的正确代码。

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim cons As New SQLite.SQLiteConnection
        cons.ConnectionString = "Data Source=C:\database.s3db; Version=3"
        cons.Open()

        Using tx = cons.BeginTransaction()

            Dim cmd As SQLite.SQLiteCommand
            cmd = cons.CreateCommand()

            For i As Integer = 0 To 1000
                Try
                    cmd.CommandText = "INSERT INTO table1 VALUES('" & i & "')"
                    cmd.ExecuteNonQuery()
                Catch ex As Exception
                End Try
            Next

            tx.Commit()
            cmd.Dispose()
        End Using

        cons.Close()
End Sub
4

1 回答 1

1

正如我所提到的,使用参数化查询、不吞下异常以及在必要时使用语句的正确方法看起来像这样。 请注意,这不是最快的方法

Private Sub InsertRows()
    Using conn As New SqlConnection
        conn.Open()
        Using tx = conn.BeginTransaction()
            For i As Integer = 0 To 1000
                Using cmd = conn.CreateCommand() 'Proper using statements wherever necessary
                    Try
                        cmd.CommandText = "INSERT INTO table1 VALUES(@ColumnName)" 'Paramertized queries
                        cmd.Parameters.AddWithValue("@ColumnName", i)
                        cmd.ExecuteNonQuery()
                    Catch ex As Exception
                        logger.ErrorException(ex) 'Logging the exception or shoe messagebox
                    End Try
                End Using
            Next
        End Using
    End Using
End Sub

理想情况下,如果在执行相同任务的紧密循环中出现异常,则不应继续执行。如果一个人失败了,那么一切都有可能失败。因此,在这种情况下,您应该删除循环内的 try/catch 并将其包裹在 for 循环上。

于 2013-09-29T07:44:56.100 回答