将文本文件中的数据插入C#中的表中
本文关键字:插入 数据 文本 文件 | 更新日期: 2023-09-27 17:59:41
我有一个看起来像的文本文件
word
love
book
...
...
我的SQL Server中有一个表。该表有一列column1
。
如何从C#winform中的文本文件将数据插入column1
??
起初,我会开始逐行读取文件,并将行值插入到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打开与数据库的数据库连接。
并通过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
}
这个会起作用:
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();