【问题标题】:Insert data from a text file into a table in C# [closed]将文本文件中的数据插入到 C# 中的表中[关闭]
【发布时间】:2013-02-17 14:56:11
【问题描述】:

我有一个看起来像

的文本文件
word
love
book
...
...

我的 SQL Server 中有一个表。该表有一个列column1

如何在 C# winform 的文本文件中将数据插入column1??

【问题讨论】:

  • 我已经添加了答案。但请注意,下次在要求“你所有的工作”之前表明你正在尝试某事。

标签: c# database winforms sql-server-2008


【解决方案1】:

首先我会开始逐行读取文件并将行值插入到List<string>

这可以通过StreamReader 完成。它是System.IO - 命名空间的一部分。

List<string> myValues = new List<string>();
string line;    
// Read the file and display it line by line.
System.IO.StreamReader file = 
   new System.IO.StreamReader("c:\\test.txt");
while((line = file.ReadLine()) != null)
{
   myValues.Add(line);
}

然后通过OleDB 打开与您的数据库的 DB-Connection。

然后通过INSERT INTO 语句将值插入到您的数据库中。

例如:

private void InsertMyValue(string myValue){
     dbconnection.Open();
     string setValues = "INSERT INTO YourTable(myColumn) VALUES ('" + myValue+ "');";
     OleDbCommand cmd = new OleDbCommand(setValues, dbconnection);
     cmd.ExecuteNonQuery();
     dbconnection.Close();
}

然后在foreach - 子句中调用方法:

foreach(string myLine in myValues){ //Go through the List with all the Lines
       dbconnection.InsertMyValue(myLine); //Get every item in the List and call the Insert-Method
}

【讨论】:

  • 感谢您不只是提供完整的代码解决方案。
【解决方案2】:

这个可以用:

var a = StreamReader("file.txt");
List<String> words = new List<String>();
While(String line = a.ReadLine())
{
    context.someTable.Add(new someTable(){column1=line});
}
context.SaveChanges();

【讨论】:

    猜你喜欢
    • 2017-12-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-22
    • 1970-01-01
    • 2013-01-17
    • 2021-05-06
    相关资源
    最近更新 更多