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

How to read data from text file and store in database table using C#?

#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

以上是文本文件格式。 here # 定义产品的类别名称。'Cola 2' 定义产品名称和价格。其中产品名称是 Cola,价格是 2。现在如何将此数据添加到我的产品中 table.I 我正在使用 c# 和 SQL。谢谢

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

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();
        }
    }
}

您可以使用类似这样的方式写入数据库。只需创建您的 SQL 连接。我建议使用 entity framework。看看这个 link for entity framework。 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();
        }
    }

你可以试试这样:

  1. 按换行符拆分
  2. 通过正则表达式找到匹配的行
  3. Select 捕获组 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);
}