将文本文件中的数据插入表SQL Server

时间:2014-06-15 13:44:35

标签: c# sql-server file-io

我有一个大文本文件,即Samples.txt文件,每8行是一行插入sql server中的表,并且数据在上述文本文件中采用以下格式,

  

公司名称:Xpress Care

     

部门:运输和储存

     

运营类型:物流服务

     

许可证号:D-39277

     

到期日:2012-07-18

     

联络电话:0771709155/0789444211

     

电子邮件:naikmalemail@hotmail.com

     

地址:4区Taemany街4号119号房屋

到目前为止,我编写了以下代码,试图将其转换为格式,以便我可以像下面那样插入到表中。

insert into table(company, sector, operation, license, expiry, contact, email, address) Values ('Xpress Care','Transportation and storage','Logistic Services','D-39277','2012-07-18', '0771709155 / 0789444211','naikmalemail@hotmail.com','House 119, Street 4, Taemany, District 4');

这是我写的代码:

static void Main(string[] args)
    {
        int counter = 0;
        int linecounter = 1;
        string line;

        // Read the file and display it line by line.
        System.IO.StreamReader file =
        new System.IO.StreamReader("c:\\sample.txt");
        while ((line = file.ReadLine()) != null)
        {
            Console.WriteLine(line);
            // splite with the : delimeter
            string[] values = line.Split(':');
            //Console.WriteLine("column name:- {0} value:- {1}",values[0],values[1]);

            //hashtable to store the key value pairs from the text file
            Hashtable myHT = new Hashtable();

            // I AM STUCK here!!! I want to add to and keep the values for 8 lines 
            myHT.Add(values[0], values[1]);

//if linecounter is 8 then I have the values for one new row to be inserted  in the table
            if (linecounter == 8)
            {
                Console.WriteLine("\n\r code to insert the  values in the query example below from the hashtable\n\r");

// insert into table(company, sector, operation, license, expiry, contact, email, address) Values ('Xpress Care','Transportation and storage','Logistic Services','D-39277','2012-07-18', '0771709155 / 0789444211','naikmalemail@hotmail.com','House 119, Street 4, Taemany, District 4');


                 // reset the linecounter and empty the hashtable here for the next row to insert
                linecounter = 0;
            }

            linecounter++;
            counter++;
        }

        file.Close();

        // Suspend the screen.
        Console.ReadLine();
    }

我想要对代码做的是我想要将键值对添加到HashTable中并保持8行,这样我就可以使用8个值插入到8列中if(linenumber==8)条件部分中的表,但现在它只保留最后一行的值。

我将非常感谢您的帮助和想法。如果您无法理解这个问题,请告诉我,我会解释更多细节,或者是否有其他方法可以解决这个问题。

4 个答案:

答案 0 :(得分:0)

您似乎需要在循环外移动HashTable的声明和初始化,并在完成八行读取后清除它

static void Main(string[] args)
{
    int counter = 0;
    int linecounter = 1;
    string line;

    //hashtable to store the key value pairs from the text file
    Hashtable myHT = new Hashtable();

    // Read the file and display it line by line.
    System.IO.StreamReader file =
    new System.IO.StreamReader("c:\\sample.txt");
    while ((line = file.ReadLine()) != null)
    { 
        ....

        // Continue to add values to the hashtable until you reach the 8 row boundary
        myHT.Add(values[0], values[1]);

        if (linecounter == 8)
        {
            ..... insert ...

             // reset the linecounter and empty the hashtable here for the next row to insert
            linecounter = 0;
            myHT.Clear();
        }

        linecounter++;
        counter++;
    }

这部分内容。我建议你为自己的工作使用不同的课程。在你的情况下,我会使用Dictionary<string,string>来解决问题的强类型方法

答案 1 :(得分:0)

您必须首先创建包含所有目标字段的表。然后

LOAD DATA INFILE '../sample.txt' INTO TABLE PerformanceReport;

默认情况下,LOAD DATA INFILE使用制表符分隔,每行一行,所以应该很好地接受它。

答案 2 :(得分:0)

如果TXT文件中的格式始终相同,为什么不使用它..

`while((line = file.ReadLine())!= null)         {             Console.WriteLine(线);             //与:delimeter分裂             string [] values = line.Split(&#39;:&#39;);             if(values [0] ==&#34; Company Name&#34;)company = value [1];

        if ((line = file.ReadLine()) != null)
        string[] values = line.Split(':');
        if (values[0]== "Sector") Sector= value[1];
          ...
          ...
        insert into table(company, sector, operation, license, expiry, contact, email, address)
        (@company, @sector,.....
        ///please insure injection protection 
      }`

答案 3 :(得分:0)

如果它是一个大文件,您可以将数据存储在DataTable(System.Data.DataTable)中,然后使用SqlBulkCopy(System.Data.SqlClient.SqlBulkCopy)快速写入。代码看起来像这样:

        System.IO.StreamReader file = new System.IO.StreamReader(@"c:\sample.txt");
        string line = null;
        int linecounter = 0;

        //structure to hold data to be written to the database
        System.Data.DataTable table = new System.Data.DataTable();
        table.Columns.Add("company");
        table.Columns.Add("sector");
        table.Columns.Add("operation");
        table.Columns.Add("license");
        table.Columns.Add("expiry");
        table.Columns.Add("contact");
        table.Columns.Add("email");
        table.Columns.Add("address");


        System.Data.DataRow row = null;
        while ((line = file.ReadLine()) != null)
        {
            //create a new table row if the line is {0,8,16,...}
            if (linecounter % 8 == 0)
                row = table.NewRow();

            string[] values = line.Split(':');

            //put the data in the appropriate column based on "linecounter % 8"
            row[linecounter % 8] = values[1];

            //add the row to the table if its been fully populated
            if (linecounter % 8 == 7)
                table.Rows.Add(row);

            linecounter++;
        }

        file.Close();

        string connectionString = "<CONNECTION STRING GOES HERE>";
        using (System.Data.SqlClient.SqlBulkCopy copy = new System.Data.SqlClient.SqlBulkCopy(connectionString))
        {
            copy.DestinationTableName = "MyTable";
            copy.WriteToServer(table);
        }

您可以在Connection strings Reference

获取有关创建连接字符串的帮助

注意:此方法假设您已经创建了一个名为&#34; MyTable&#34;在SQL Server中,它具有在DataTable中指定的8个varchar列。