当前位置: 动力学知识库 > 问答 > 编程问答 >

database - Insert data from a text file into a table in C#

问题描述:

I have text file which looks like

word

love

book

...

...

and I have a table in my SQL Server. The table has a columm column1.

How can I insert data into column1 from the text file in C# winform ??

网友答案:

At first I would start reading the file line by line and inserting the line values into a List<string>.

This can be done with a StreamReader. It is part of the System.IO - namespace.

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

Then open a DB-Connection to your DB via OleDB.

And insert the values into your database via an INSERT INTO Statement.

For Example:

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

Then call the method in a foreach - clause:

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
}
网友答案:

This one will work:

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();
分享给朋友:
您可能感兴趣的文章:
随机阅读: