现在将一个文本文件中的N条数据分次分批导入到数据库中。比如,目标文本中有100条记录,我一次读10条后,先将这10条插入到数据库;然后再接着上次的再读10条,插入,直到将所有的数据插入到数据库。 比如,我数据库中的表中有两个字段,一个编号:ID,一个类别:KIND,现在文本中的数据如下:
001ABCE100000
002ABCE200000
003ABCE100000
004EFGE200000在上面的这段文本中,每条数据中的前三位,比如第一条中的001就对应数据库中的编号ID字段,E1对应数据中的类别 KIND 字段,其中001后面的ABC和最后的几个0都是不要的数据,其中类别的种类只有E1和E2两种。如果现在目标文本中有这样的字段1000条,现在我要分次分批插入到数据库中,比如一批50条。 希望各位帮个忙,指点一下。谢谢了!
001ABCE100000
002ABCE200000
003ABCE100000
004EFGE200000在上面的这段文本中,每条数据中的前三位,比如第一条中的001就对应数据库中的编号ID字段,E1对应数据中的类别 KIND 字段,其中001后面的ABC和最后的几个0都是不要的数据,其中类别的种类只有E1和E2两种。如果现在目标文本中有这样的字段1000条,现在我要分次分批插入到数据库中,比如一批50条。 希望各位帮个忙,指点一下。谢谢了!
Option Explicit
Private conn As ADODB.ConnectionPrivate Sub Form_Load()Dim dbfilename As String
Dim ConnectString As String
Dim i As Integer
Set conn = New ADODB.Connectiondbfilename = App.Path & "\article.mdb"
ConnectString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & dbfilename & ";Persist Security Info=False;"
conn.Open ConnectString
conn.CursorLocation = adUseClientEnd SubPrivate Sub Command1_Click() Dim i As Integer
Dim thstr As String
Dim str1 As String
Dim str2 As String
fileName = App.Path & "\test.txt" If Dir(fileName) <> "" Then
'加载数据
Open fileName For Input As #1
i = 1
Do While Not EOF(1)
Line Input #1, thstr
str1 = Left(thstr, 3)
str2 = Mid(thstr, 7, 2)
conn.Execute "insert into tree(id,kind) values('" & str1 & "','" & str2 & "')"
Loop
Close #1
End If
End Sub
Dim objSystem As New FileSystemObject, objStream As TextStream, intLoop As Integer
Dim strSql(50) As String, strRead As String, blnNoerr As Boolean
blnNoerr = True
Set objStream = objSystem.OpenTextFile("ÎļþÃû.txt")
While blnNoerr
For intLoop = 0 To 49
strRead = objStream.ReadLine
On Error Resume Next
If Err.Number <> 0 Then 'Óöµ½Îļþβ³ö´íÌø³öÑ­»·
Exit For
End If
On Error GoTo 0
strSql(intLoop) = "Insert Into ±íÃû Values ('" & Left(strRead, 3) & "','" & Mid(strRead, 7, 2) & "')"
Next
For intLoop = 0 To 49
If strSql(intLoop) <> "" Then
'Ö´ÐÐstrSqlÀï±£´æµÄSQLÓï¾ä
strSql(intLoop) = ""
Else
Exit For
End If
Next
If Err.Number <> 0 Then blnNoerr = False
Wend
Dim objSystem As New FileSystemObject, objStream As TextStream, intLoop As Integer
Dim strSql(50) As String, strRead As String, blnNoerr As Boolean
blnNoerr = True
Set objStream = objSystem.OpenTextFile("文件名.txt")
While blnNoerr
For intLoop = 0 To 49
strRead = objStream.ReadLine
On Error Resume Next
If Err.Number <> 0 Then '遇到文件尾出错跳出循环
Exit For
End If
On Error GoTo 0
strSql(intLoop) = "Insert Into 表名 Values ('" & Left(strRead, 3) & "','" & Mid(strRead, 7, 2) & "')"
Next
For intLoop = 0 To 49
If strSql(intLoop) <> "" Then
'执行strSql里保存的SQL语句
strSql(intLoop) = ""
Else
Exit For
End If
Next
If Err.Number <> 0 Then blnNoerr = False
Wend
读一条插一条,当数据条数多时会很慢,你的方法好象只能插50条啊/to northwolves(狼行天下):
能不能具体点?