批量从Excel插入到SQLite而不使用TXT或CSV文件

时间:2017-03-30 13:47:52

标签: excel vba sqlite

我遇到了问题,希望能得到你们的任何意见。

基本上,我需要在VBA中编写代码,这使我能够从excel到sqlite获取数据表。

我已设法使用此代码执行此操作:

Sub Scrivi()
    Dim objConnection As Object, objRecordset As Object
    Dim strDatabase As String

    Set objConnection = CreateObject("ADODB.Connection")

    strDatabase = "DRIVER={SQLite3 ODBC Driver};Database=" & Application.ActiveWorkbook.Path & "\TestDB.db;"

    Query = "drop table FUND; create table FUND (Fund_Code, Fund_Name, End_Date, PRIMARY KEY('Fund_Code'));"
    riga = 3
    colonna = 1
    While Not (IsNull(ActiveSheet.Cells(row, column).Value) Or IsEmpty(ActiveSheet.Cells(row, column).Value))
        Query = Query & "insert into FUND values('" & Cells(row, column) & "','" & Cells(row, column + 1) & "','" & Cells(row, column + 2) & "');"
        row = row + 1
    Wend

    objConnection.Open strDatabase
    objConnection.Execute Query
    objConnection.Close 
End Sub

现在我想用一种批量插入来改变我说row = row + 1的迭代部分,其中程序采用整个表而不是逐行进行。

如果可能的话,我不想创建csv / txt文件。

非常感谢,任何意见都会受到赞赏。

2 个答案:

答案 0 :(得分:0)

一个非常基础的解决方案可以是首先构建批量插入的完整查询,然后一次执行查询。

例如 -

插入FUND值(val1,val2); 插入FUND值(val3,val4);

可以替换为 - 插入FUND值(val1,val2),(val3,val4)

答案 1 :(得分:0)

您可以将workheet.range中的所有数据附加到数组(变体)

Dim arr as Variant
arr = Application.Transpose(range(your_range_of_data).values)

然后,使用数组中的数据,使用此模式构建SQL查询字符串

INSERT INTO table
(column1, column2, ... )
VALUES
(expression1, expression2, ... ),
(expression1, expression2, ... ),
...;

VBA功能(写在'膝盖上',所以可能需要稍微调整一下,对不起)

Function buildQueryFromArray(arr as Variant, table as String, columns as String) as String
    Dim strSqlQuery as String * 4096 
    Dim i as Integer

    strSqlQuery = "INSERT INTO " & table & " (" & columns & ") VALUES"
    For i=LBound(arr, 1) to UBound(arr, 1)
        strSqlQuery = strSqlQuery & "(" & arr(i,1) & ", " & arr(i,2) & "etc" & "),"
    Next i
    buildQueryFromArray = Left(strSqlQuery, len(strSqlQuery)-1) & ";"
End Function

使用数组而不是直接从工作表中获取数据的原因是:它的速度要快得多。您可以在此处阅读更多内容:http://www.cpearson.com/excel/ArraysAndRanges.aspx lemme知道这是否适合你:)

修改
Ad1:你是对的,我们实际上不想转置它。 然而,我习惯于这样写,因为本主题在第7篇文章中有详细描述的原因: mrexcel.com/forum/ Why we use application.transpose?
Ad2:不,如果这是你的问题,它不必在功能,但它使代码更清洁,更可重用。您可以在下面找到内联解决方案:

Sub Scrivi()
Dim objConnection As Object, objRecordset As Object
Dim strDatabase As String, strQuery as String 

Set objConnection = CreateObject("ADODB.Connection")

strDatabase = "DRIVER={SQLite3 ODBC Driver};Database=" & Application.ActiveWorkbook.Path & "\TestDB.db;"

strQuery = "drop table FUND; create table FUND (Fund_Code, Fund_Name, End_Date, PRIMARY KEY('Fund_Code')); insert into FUND values"

'determine how many rows of data there is
Dim lastRow as Integer
lastRow = ActiveSheet.Range("A:A").Find("*", LookIn:=xlFormulas, SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row

'transfer all data from range to array
'range: from A3 to Cx, where x equals to lastRow
Dim arr as Variant
arr =

 ActiveSheet.Range("A3:C" & lastRow).Value

    'add all records from arr into single SQL query
    'Lbound(xArray, xDimension)/Ubound(xArray, xDimension) - returns integer equal to first/last xArray item in xDimension. Everyday-use function. Google some more to have better insight of whats going on
    Dim i as Integer
    For i=Lbound(arr,1) to Ubound(arr,1)
    strQuery = strQuery & "(" & arr(i,1) & "," & _
                                arr(i,2) & "," & _
                                arr(i,3) & "),"
Next i

'from the strQuery - swap last comma for semi-colon
strQuery = Left(strQuery, len(strQuery)-1) & ";"

objConnection.Open strDatabase
objConnection.Execute strQuery
objConnection.Close 

Lemme知道一切都很清楚:)