将多个记录插入Access DB

时间:2013-10-04 07:10:16

标签: sql vb.net ms-access oledb

使用VB.net将多个记录插入Access数据库的最有效方法是什么?

我有一个具有多个属性的对象列表,这些属性是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

我假设有一种更好,更有效的方法,但我找不到它!

1 个答案:

答案 0 :(得分: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 Injection attack

的风险