我需要在MySQL表中插入六个txt文件。我想将文件txt10.txt
插入表D1中,将文件txt20.txt
插入表D2中,将文件txt30.txt
插入表D3中,等等。但是所有文本文件都插入到所有MySQL表中。
我的下面的代码:
Arr1 = Array("txt10", "txt20", "txt30", "txt40", "txt50", "txt60")
Arr2 = Array("D1", "D2", "D3", "D4", "D5", "D6")
For K = 0 To UBound(Arr1)
For I = 0 To UBound(Arr2)
SQL = " FLUSH TABLE `tbl_" & Arr2(I) & "_" & Year(Date()) & "`; "
cn.Execute(SQL)
SQL = " LOAD DATA LOCAL INFILE 'D:\\nOpen\\" & Arr1(K) & ".txt' "
SQL = SQL & " INTO TABLE `tbl_" & Arr2(I) & "_" & Year(Date()) & "` FIELDS TERMINATED BY ';' LINES TERMINATED BY '\n' IGNORE 1 LINES;"
cn.Execute(SQL)
Next
Next
编辑#1
在您的代码中,我有错误:
数组索引超出范围
在这一行:
tbl = Arr2(n)
新代码:
Arr1 = Array("txt10", "txt20", "txt30", "txt40", "txt50", "txt60")
Arr2 = Array("D1", "D2", "D3", "D4", "D5", "D6")
For n=0 To UBound(Arr1)
txt = Arr1(n)
tbl = Arr2(n)
SQL = " FLUSH TABLE `tbl_" & tbl & "_" & Year(Date()) & "`; "
cn.Execute(SQL)
SQL = " LOAD DATA LOCAL INFILE 'D:\\nOpen\\" & txt & ".txt' "
SQL = SQL & " INTO TABLE `tbl_" & tbl & "_" & Year(Date()) & "` FIELDS TERMINATED BY ';' LINES TERMINATED BY '\n' IGNORE 1 LINES;"
cn.Execute(SQL)
Next
答案 0 :(得分:3)
是的,是的。运行两个For
会循环执行操作,这将为您提供两个输入数组元素的所有可能组合。
您真正想要的是使用一个循环并选择每个数组的相应元素:
For n=0 To UBound(Arr1)
txt = Arr1(n)
tbl = Arr2(n)
'now insert txt into tbl
Next
或者,您可以建立文件到表的映射(反之亦然),这样您就不必依赖两个大小相同的数组:
Set map = CreateObject("Scripting.Dictionary")
map.Add "txt10", "D1"
map.Add "txt20", "D2"
...
For Each txt In map.Keys
tbl = map(txt)
'now insert txt into tbl
Next
无论选择哪种方式,都不要通过字符串串联来构建SQL查询。它将打开您的代码到SQL injection。请改用prepared statements。