【问题标题】:Import CSV file to SQLITE database via VBA - Access通过 VBA 将 CSV 文件导入 SQLITE 数据库 - Access
【发布时间】:2020-03-28 11:09:56
【问题描述】:

我在 Access VBA 中有一个项目,我需要将 CSV 文件(最大 15MB)自动导入到链接的 SQLITE db 中。全部在本地机器上完成。 类似于 MS SQL(如下所述)可以通过查询或 VBA 实现吗?

strConn = "DRIVER=ODBC Driver 13 for SQL Server;Server=" & serv & ";Database=" & databs & ";Uid=" & usern & ";Password=" & pwd & ";"
cn.Open strConn

Strsql1 = "BULK INSERT dbo.SEARCHUSRTABLE2 FROM '" & insertfile & "' WITH(FIELDTERMINATOR = ',',ROWTERMINATOR = '\n');"
Set rs = cn.Execute(Strsql)

【问题讨论】:

  • SQLite?那么,您为什么要使用带有 T-SQL 命令的 SQL Server ODBC 驱动程序,例如BULK INSERT
  • 这只是一个例子——询问 SQLITE 是否有类似的东西。在第二句话中。

标签: sql vba sqlite ms-access


【解决方案1】:

好的,我们需要一些东西。

首先,我们需要来自 Access:

浏览到 csv 文件 - 选择

将 csv 文件导入表格。

现在,导出到 SQLite。

但是,我们在这里遗漏了几个问题。

首先,SQLite 数据库是同一个数据库并且一直在同一个位置吗?

您是否安装了 SQLite ODBC 驱动程序,并且您是否能够从 Access 链接到 SQLite?

所以,我们有点需要整理以上所有内容。尤其是与 SQLite 的连接。

不清楚您是否计划/想要为每个 csv 导入创建一个新表,或者您要清除一个表并重新填充?

假设如下:

您有一个通过 Access 工作的与 SQLite 的链接表。

你可以在Access中点击这个链接表,你可以看到/查看甚至编辑来自Access的数据,但是数据库和表当然是到SQLite的链接表。

如果以上所有方法都有效? 到目前为止,以上所有内容都需要零代码。所以你“需要”让上述部分工作。

而且我们假设每次 csv 导入都是为了在 SQLite 数据库中创建一个新表?

那么代码将如下所示:

将此子代码粘贴到标准访问代码模块中。

保存它,然后在代码中的任意位置使用光标,按 f5 运行。

  Sub CsvImportToSQL()

      Dim strCsvFile    As String

      Dim f             As Object
      Set f = Application.FileDialog(3)
      f.Filters.Clear
      f.Filters.Add "Csv file", "*.csv"
      If f.Show = False Then
        ' no file selected - quite
        Exit Sub
      End If

     Dim strFromTable  As String
     strFromTable = f.SelectedItems(1)

     Dim strTable      As String
     ' get only name of file without extension for Access table name
     strTable = Mid(strFromTable, InStrRev(strFromTable, "\") + 1)
     strTable = Left(strTable, InStr(strTable, ".") - 1)

     strTable = InputBox("Select table = " & strFromTable, "Inport to Access table", strTable)

     If strTable = "" Then
        ' user hit cancel - exit
        Exit Sub
     End If

     ' transfer the table into access

     DoCmd.TransferText acImportDelim, , strTable, strFromTable, True

     ' ok, now ask for table name to export to in SQLite

     Dim strSQLiteTable   As String
     strSQLiteTable = strTable

     strSQLiteTable = InputBox("Table name to export for SQLite", "SQL lite table name", strSQLiteTable)
     If strSQLiteTable = "" Then
        ' user cancel - don't transfer - exit
        Exit Sub
     End If

     ' now transfer table to SQL site

     Dim strCon As String
     strCon = CurrentDb.TableDefs("Hotels").Connect
     ' (replace above Hotels with a KNOWN WORKING LINKED table to SQLite)

     DoCmd.TransferDatabase acExport, "ODBC Database", strCon, acTable, strTable, strSQLiteTable

     MsgBox "table exported to SQLITE"



  End Sub

【讨论】:

    猜你喜欢
    • 2014-08-18
    • 1970-01-01
    • 1970-01-01
    • 2016-01-21
    • 1970-01-01
    • 2012-05-04
    • 2016-11-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多