我有看起来像的文本文件
word
love
book
...
...
我的 SQL Server 中有一个表。该表有一列column1。
如何column1从 C# winform 的文本文件中插入数据?
我有看起来像的文本文件
word
love
book
...
...
我的 SQL Server 中有一个表。该表有一列column1。
如何column1从 C# winform 的文本文件中插入数据?
起初我会开始逐行读取文件并将行值插入到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
}
这将起作用:
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();