如何将记录从文本文件添加到表中

本文关键字:添加 文件 文本 记录 | 更新日期: 2023-09-27 18:07:05

我有一个名为statelist的表,它看起来像这样:

abbrev nvarchar(2);
name   nvarchar(50);

我有一个名为state_list.txt的文本文件,其中包含如下格式的州列表:

'AL','Alabama'
'AK','Alaska'
'AR','Arkansas'

我想从文本文件中获取数据到statelist表中。是否有某种SQL插入或其他代码来做到这一点?

如何将记录从文本文件添加到表中

你没有指定的东西,如你的数据库等,但这将是我最好的猜测。我建立了一个MsSql数据库,但你可以在几个简单的步骤中调整它为mySql(首先安装mySql连接器)。我没有一个sql数据库在我的处置atm所以我没有尝试它在家里,但它应该这样工作。当然,编辑连接字符串,使其适合您的数据库

        string fileName = "state_list.txt";
        var lines = File.ReadLines(fileName);
        Dictionary<string,string> splitted = new Dictionary<string,string>();
        foreach (var line in lines)
        {
            string[] splitter = line.Split(',');
            splitted.Add(splitter[0], splitter[1]); //Add eatch splitted line to dictionary so you can use key and value to insert into table
        }

        string connStr ="server = localhost; user = root; database = yourdb; port = 3306; password = xxxxxxxxx;"; // CREATE CONNECTION WITH YOUR DATABASE INFORMATION
        SqlConnection conn = new SqlConnection(connStr);
        try
        {
            conn.Open();
            SqlCommand comm = conn.CreateCommand();
            comm.CommandText = "INSERT INTO state_list(code,area) VALUES(@code, @area)";
            foreach (KeyValuePair<string, string> pair in splitted)
            {
                comm.Parameters.Add("@code", pair.Key);
                comm.Parameters.Add("@areas", pair.Value);
                comm.ExecuteNonQuery(); // INSERT EACH PAIR INTO DATABASE
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.ToString());
        }
        conn.Close(); //CLOSE CONNECTION

(1)解析。txt文件;(2)将记录添加到DB。你可以使用实体框架,或者任何其他ORM,或者像@Jurriaan建议的那样使用ADO。

如果你正在使用实体框架,你可以使用这种方法。

   using(var context = new YourContext())
   {
        List<YourEntity> entities = new List<YourEntity>();
        File.ReadAllLines("PathToFile")
            .ToList()
            .ForEach(s =>
            {
               string[] split = s.Split(',');
               someList.Add(new YourEntity(split[0], split[1])); // Or set properties if not using a constructor.
            });
        context.YourTable.AddRange(entities);
        context.SaveChanges();
   }

我能想到的一种方法是使用ReadLine()从文本文件中读取每一行,然后在该行上使用Split(',')以获得字符串数组中的缩写和名称,然后您可以轻松地将它们添加到while循环中的数据库中。

从文件中删除',然后运行以下命令。

Bulk Insert [dbo].[TableName]
From 'C:'FileName.csv'
with
(
FIELDTERMINATOR = ',', -- For Comma Seperated File
RowTerminator = ''n' -- RowTernimator i.e new Line
)

之前做过这个,当时添加到博客- http://dotnetdevblog.blogspot.com/2007/10/bulk-inserting-from-csv-file-into.html