如何使用C#从文本文件读取数据并将其存储在数据库表中?

时间:2019-04-09 10:59:39

标签: c# database file text separator

#Softdrinks
Cola 2
Sprote 3
Fant 4
Redbull 2
#Pide-Lahmacun
Pide Mozarella 12
Pide Hackfleisch 12
Pide Feta-Hackfleisch 14
Pide Spinat 13
Pide Spinat-Ei 14
上面的

是文本文件格式。此处#定义产品的类别名称。“可乐2”定义产品名称和价格。产品名称为Cola,价格为2。现在如何将这些数据添加到我的产品表中。我正在使用c#和SQL。谢谢。

3 个答案:

答案 0 :(得分:0)

使用以下代码解析文本文件,然后使用字符串将其放入数据库。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Text.RegularExpressions;


namespace ConsoleApplication108
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.txt";
        static void Main(string[] args)
        {
            StreamReader reader = new StreamReader(FILENAME);

            string line = "";
            string category = "";
            string pattern = @"(?'name'.*)\s+(?'price'\d+)";
            while ((line = reader.ReadLine()) != null)
            {
                line = line.Trim();
                if (line.Length > 0)
                {
                    if (line.StartsWith("#"))
                    {
                        category = line.Substring(1);
                    }
                    else
                    {
                        Match match = Regex.Match(line, pattern);
                        string name = match.Groups["name"].Value.Trim();
                        string price = match.Groups["price"].Value.Trim();

                        Console.WriteLine("category : '{0}', name : '{1}', price : '{2}'", category, name, price);

                    }
                }
            }
            Console.ReadLine();
        }
    }
}

答案 1 :(得分:0)

您可以使用类似的方法将其写入数据库。只需创建您的SQL连接。我建议使用实体框架。看一下该实体框架的链接。 Insert data using Entity Framework model

    public int InsertItem(string item1, string item2, string item3)
    {
        using (var connection = CreateDBConnection())
        using (var command = connection.CreateCommand())
        {
            command.CommandText = @"
                INSERT dbo.TableName(item1, item2, item3)
                OUTPUT Inserted.Id
                VALUES (@item1, @item2, @item3)";

            command.Parameters.Add(new SqlParameter("@item1", item1));
            command.Parameters.Add(new SqlParameter("@item2", item2));
            command.Parameters.Add(new SqlParameter("@item3", item3));

            connection.Open();
            return (int)command.ExecuteScalar();
        }
    }

答案 2 :(得分:0)

您可以尝试以下操作:

  1. 由换行符
  2. 通过正则表达式查找匹配的行
  3. 选择捕获组1和2
  4. 将组映射到匿名类型
  5. 创建一个空的数据表
  6. 立即填充数据表。

The regex: (.*?)\s(\d+)

正则表达式的解释:

1st Capturing Group (.*?)
.*? matches any character (except for line terminators)
*? Quantifier — Matches between zero and unlimited times, as few times as possible, expanding as needed (lazy)

\s matches any whitespace character (equal to [\r\n\t\f\v ])

2nd Capturing Group (\d+)
\d+ matches a digit (equal to [0-9])
+ Quantifier — Matches between one and unlimited times, as many times as possible, giving back as needed (greedy)

代码:

string contents = File.ReadAllText(@"test.txt");

string pattern = @"(.*?)\s(\d+)";

var query = contents.Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries)
                .Where(x => Regex.IsMatch(x, pattern))
                .Select(x => Regex.Match(x, pattern))
                .Select(x => new
                {
                    Name = x.Groups[1].Value,
                    Value = Convert.ToInt32(x.Groups[2].Value)
                });

DataTable dataTable = new DataTable();
dataTable.Columns.Add(new DataColumn("Name", Type.GetType("System.String")));
dataTable.Columns.Add(new DataColumn("Value", Type.GetType("System.Int32")));

foreach (var item in query)
{
    DataRow dr = dataTable.NewRow();
    dr["Name"] = item.Name;
    dr["job1"] = item.Value;
    dataTable.Rows.Add(dr);
}