我有很多文本文件,其内容如下:
LOG_NAME=LOGX1245; LOT_NO=NA; STEP=NA; NO=CS84E869500115; TIME_START=20190506 094715; TIME_END=20190506 094715
我需要阅读文本文件并插入数据库。 列名称是第一个字段,值是第二个字段。 如何读取文本文件并将每一行插入数据库?
我要做的是:
For Each file In fso.GetFolder("C:\Data").Files
Set otf = objFSO.OpenTextFile(file, 1)
Do Until otf.AtEndOfStream
line = otf.ReadLine
If Mid(line, 1, 12) = "LOG_NAME" Then
datalog = Trim(Split(line, "=")(1))
End If
If Mid(line, 1, 10) = "LOT_NO" Then
PT = Trim(Split(line, "=")(1))
End If
If Mid(line, 1, 4) = "STEP" Then
TestStep = Trim(Split(line, "=")(1))
End If
If Mid(line, 1, 11) = "NO" Then ...
Loop
otf.Close
Next
这是我要查询的地方。如何根据我从文本文件中获取的值查询SQL INSERT语句?有没有更简单的方法?
Dim query
Set rsObj = CreateObject("ADODB.Recordset")
query = "Insert in"
On Error Resume Next
rsObj.Open query, connObj
答案 0 :(得分:0)
尝试以下代码
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objConn = CreateObject("ADODB.Connection")
objConn.Open "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=C:\Users\Desktop\Data.accdb"
For Each objFile In objFSO.GetFolder("C:\Users\Desktop\Data").Files
Set objDataFile = objFSO.OpenTextFile(objFile.Path, 1)
arrData = Split(objDataFile.ReadAll, vbNewLine) 'store file data in array
objDataFile.Close
varValues = Empty: varFields = Empty
For i = LBound(arrData) To UBound(arrData)
arrRowData = Split(arrData(i), "=")
varFields = varFields & "[" & arrRowData(0) & "]," 'square bracket to avoid reserve keyword as field name
arrRowData(1) = Left(arrRowData(1), Len(arrRowData(1)) - 1) 'remove last semicolon
varValues = varValues & "'" & arrRowData(1) & "',"
Next
varFields = Left(varFields, Len(varFields) - 1) 'remove last comma
varValues = Left(varValues, Len(varValues) - 1) 'remove last comma
objConn.Execute "INSERT INTO Data(" & varFields & ") VALUES(" & varValues & ")"
Next
Set objFSO = Nothing
objConn.Close
Set objConn = Nothing
我已经使用Access DB来测试代码。另外,我假设“数据”文件夹中的文本文件相似,并且只包含适合数据库插入的数据。
运行代码之前的数据库
运行代码后的数据库
我测试了Data文件夹中的2个文本文件。