从文本文件读取数据并插入数据库

时间:2013-12-06 07:32:39

标签: asp.net vb.net sql-server-2008 sql-insert

我想逐行读取文本文件中的数据,并将数据插入数据库的每一行。

我现在想的是逐行阅读并在每行插入数据库。我在这里问的是有更好的主意吗?比如我们可以做什么来一次插入数据而不是逐行循环并插入记录?我在每天需要存储的文本文件中有大约500行,所以性能是我的问题。

请注意,我需要在数据库中将每行插入一行。数据以逗号分隔,因此我需要拆分它们并将它们插入特定列。

任何建议?

4 个答案:

答案 0 :(得分:3)

Imports System
Imports System.IO
Imports System.Collections

Module Module1

    Sub Main()
        Dim objReader As New StreamReader("c:\test.txt")
        Dim sLine As String = ""
        Dim arrText As New ArrayList()

        Do
            sLine = objReader.ReadLine()
            If Not sLine Is Nothing Then
                arrText.Add(sLine)
            End If
        Loop Until sLine Is Nothing


        objReader.Close()
       Using command As New SqlCeCommand("INSERT INTO table(col1) VALUES(@data1)", Con)
       command.Parameters.AddWithValue("@data1", "")           
  For Each sLine In arrText
                command.Parameters("@data1").Value = sLine
                command.ExecuteNonQuery()
            Next

       End Using
    End Sub
End Module

答案 1 :(得分:1)

您可以先将文本文件放入数据表中(因为它是基于内存的,并且没有任何循环访问服务器而导致数据表不会出现任何性能问题),而是使用Bulkcopy功能将其插入数据库。我假设数据将被插入SQL Server数据库。您可以在此处使用SQLBulkCopy示例代码:

private void BulkInsert()
{
    SqlBulkCopy bulkCopy = new SqlBulkCopy("Server=ServerName;Database=test;Trusted_Connection=True;", 
    SqlBulkCopyOptions.TableLock);
    bulkCopy.DestinationTableName = "target_table";
    bulkCopy.WriteToServer(Text2Table());
}

private DataTable Text2Table()
{
    DataTable dt = new DataTable();

    StreamReader sr = new StreamReader(@"c:\test\test.txt");
    string input;

    while ((inrecord = sr.ReadLine()) != null)
    {
        string[] values = inrecord.Split(new char[] { '|' });
        dr = dt.NewRow();
        dr["column1"] = values[0];
        dr["column2"] = values[1];
        dr["column3"] = values[2];
        dr["column4"] = values[3];
        dt.Rows.Add(dr);
    }
    sr.Close();
    return dt;
}

答案 2 :(得分:0)

我觉得这很容易。

import java.io.File;
import java.io.FileNotFoundException;

import java.util.Scanner;

public class ScannerReadFile {

    public static void main(String[] args) {

FileInputStream fstream = new FileInputStream("textfile.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));

String strLine;
int row =0;
int col;

while ((strLine = br.readLine()) != null)   {

       Scanner scanner = new Scanner(strLine);
       String token="";
       while(scanner.hasNext()){
        token = scanner.next();
        for(int i = 0; i<token.length();i++){

            if(token.charAt(i)!=','){
                record += token.charAt(i);
            }
            else{
            insert into table values ( record )  
            record = "";
            }
        }
          row++;       
       } }

答案 3 :(得分:0)

性能问题是由于正常插入数据库 - 而不是因为读取文件。

为了解决这个问题,我建议你使用strongtyped数据表 - 因为你只是插入,只是在这个.Net数据表中添加新行,最后一次性将它提交给DB(使用SqlDataAdapter)

关于阅读文件,我建议你使用现有的vb.net库:Microsoft.VisualBasic.FileIo.TextFiledParser(ref:http://msdn.microsoft.com/en-us/library/microsoft.visualbasic.fileio.textfieldparser(v=vs.110).aspx)。

当然,你有另一个选择,而不是使用DataTable,生成纯文本SQL插入查询会执行得更好,输出查询将如下:

INSERT INTO tblTarget(Id, Col1, Col2)
Values (1, 'Row1.Val1', 'Row1.Val2'),
       (2, 'Row2.Val1', 'Row2.Val2'),
       (3, 'Row3.Val1', 'Row3.Val2'),
       (4, 'Row4.Val1', 'Row4.Val2'),
       ...

希望它有所帮助...

相关问题