我在Access VBA中有一个项目,需要自动将CSV文件(最大15MB(导入链接的SQLITE数据库。全部在本地机器上完成。类似于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)
好的,我们需要一些东西。
首先,我们需要Access:
浏览到csv文件–选择
将csv文件导入表格。
现在,导出到SQLite。
但是,我们遗漏了几个问题。
首先,SQLite数据库是不是一直都是同一个数据库,在同一个位置?
您是否安装了SQLite ODBC驱动程序,是否能够从Access链接到SQLite?
所以,我们需要解决以上所有问题。尤其是与SQLite的连接。
不清楚你是计划/想为每个csv导入创建一个新表,还是要清除一个表,然后重新填充?
假设如下:
您有一个从Access链接到SQLite的表。
您可以在Access中单击此链接表,您可以查看/查看甚至编辑FROM 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