0

使用 VB.net 将多条记录插入 Access DB 的最有效方法是什么?

我有一个具有多个属性的对象列表,这些属性是INSERT查询的值,我想知道我是否可以将它们全部插入而不是遍历对象列表,构建查询字符串并一一执行查询,这是非常减缓。

我所拥有的粗略示例:

    For Each Val In ValueList

        ValueString = Val.X.ToString & ", "
        ValueString += Val.Y.ToString & ", "
        ValueString += Val.Z.ToString

        SQLValueList.Add(ValueString)

    Next

    Dim cmd As OleDb.OleDbCommand
    Dim strConnection As String
    Dim strSql As String = Nothing

    strConnection = _
            "Provider=Microsoft.ACE.OLEDB.12.0;" & _
            "Data Source=C:\db.accdb;" & _
            "User ID=Admin;Password=;"

    For Each ValueString As String In SQLValueList

        strSql = "INSERT INTO Results (FldX, FldY, FldZ)" &
                    "VALUES ( " & ValueString & ");"

        cmd = New OleDb.OleDbCommand(strSql)
        cmd.Connection = New OleDb.OleDbConnection(strConnection)
        cmd.Connection.Open()
        cmd.ExecuteNonQuery()

    Next

我假设有一种更好、更有效的方法可以做到这一点,但我一直找不到!

4

1 回答 1

3

是的,参数化查询

Imports System.Data.OleDb
.......

Dim strConnection As String
Dim strSql As String = Nothing

strConnection = _
        "Provider=Microsoft.ACE.OLEDB.12.0;" & _
        "Data Source=C:\db.accdb;" & _
        "User ID=Admin;Password=;"

strSql = "INSERT INTO Results (FldX, FldY, FldZ) VALUES ( ?, ?, ?)"
using cn = new OleDbConnection(strConnection)
using cmd = new OleDbCommand(strSql, cn)
    cn.Open()
    ' HERE all the parameters are added with a string dummy value. '
    ' This should be changed if one of the underlying field is of different type '
    ' For example, if FldX is of type integer your need to write '
    '  cmd.Parameters.AddWithValue("@p1", 0) and then in the loop code '
    '  '
    '  cmd.Parameters(0).Value = val.X  or  '
    '  cmd.Parameters(0).Value = Convert.ToInt32(val.X) if val.X is not an integer but  convertible to... '


    cmd.Parameters.AddWithValue("@p1", "")
    cmd.Parameters.AddWithValue("@p2", "")
    cmd.Parameters.AddWithValue("@p3", "")
    For Each val In ValueList
        cmd.Parameters(0).Value = val.X.ToString()
        cmd.Parameters(1).Value = val.Y.ToString()
        cmd.Parameters(2).Value = val.Z.ToString()
        cmd.ExecuteNonQuery()
   Next
End Using
End Using

这只是一个示例,因为不清楚您的 ValueList 中存储了哪种数据(字符串、整数、双精度日期?),但我希望这个想法很清楚。创建一个带有 3 个参数的命令对象(每个要插入的字段一个),将每个参数添加到带有虚拟值的命令集合中(在示例中,每个参数都包含一个字符串值,但您需要为基础字段类型添加正确的数据类型)。此时只需在您的值上循环一次并执行查询。

请远离字符串连接来构建 sql 命令,特别是当您的用户键入要连接的字符串值时。您冒着Sql 注入攻击的风险

于 2013-10-04T07:15:14.000 回答