2014-02-19 52 views
0

所以我想要做的是非常不同我试图在这种格式的文本文件中插入一组零件号码。C#批量从文本文件插入SQL与多个行

NTM-120 
NTM-130 
NTM-140 
NTM-150 
NTM-160 
NTM-170 
NTM-180 
NTM-190 
NTM-200 
NTM-210 

插入数据将是所有部分相同,这里是我目前如何做一个插入。

  //Inserts Feature 1 

      SqlConnection sqlCon2 = new SqlConnection("REMOVED"); 
      SqlCommand sqlCmd2 = new SqlCommand(); 
      sqlCmd2.CommandText = "INSERT INTO [Products].[Features] ([ProductID] ,[Title] ,[ViewOrder]) VALUES ('" + textBox15.Text + "', '" + textBox19.Text + "', NULL) "; 
      sqlCmd2.Connection = sqlCon2; 


      sqlCon2.Open(); 
      sqlCmd2.ExecuteNonQuery(); 
      sqlCon2.Close(); 


      //Inserts Feature 2 

      SqlConnection sqlCon3 = new SqlConnection("REMOVED"); 
      SqlCommand sqlCmd3 = new SqlCommand(); 
      sqlCmd3.CommandText = "INSERT INTO [Products].[Features] ([ProductID] ,[Title] ,[ViewOrder]) VALUES ('" + textBox15.Text + "', '" + textBox20.Text + "', NULL) "; 
      sqlCmd3.Connection = sqlCon3; 

我的主要目标是对如此选择的文本文件,并将它插入来自某些文本框相同的数据(特征)为每个文本框中的零件,并且所述partnumbers必须被插入到柱以及他们是productID。

这可能吗?

请帮忙谢谢。 :d

+1

我不完全理解你的问题..但为什么你不使用参数化查询? – gbianchi

+0

我试图为不同的零件号插入相同的数据。 –

+0

好吧,让我们试图澄清你的问题..你是从一个文本文件(为什么你的代码中有文本框?)插入SQL数据库?你的主要问题在哪里? – gbianchi

回答

0

我不明白如何在你的问题用一个文件,但如果你想在同一篇文章(textbox15)中添加文本框的许多价值,你可以做到这一点

List<TextBox> texts = new List<TextBox> { textBox16, textBox17, textBox20 }; 
foreach (var textBox in texts) 
{ 
    using (SqlConnection sqlCon2 = new SqlConnection("REMOVED")) 
    { 
     using (SqlCommand sqlCmd2 = new SqlCommand {CommandText = "INSERT INTO [Products].[Features] ([ProductID] ,[Title] ,[ViewOrder]) VALUES ('" + textBox15.Text + "', '" + textBox.Text + "', NULL) ", Connection = sqlCon2}) 
     { 
      sqlCon2.Open(); 
      sqlCmd2.ExecuteNonQuery(); 
     } 
    } 
} 

更新

如果你想插入值存在于你的文本文件的NTM是你第一部分和120中的第二

using (StreamReader sr = new StreamReader(filePath)) 
{ 
    while (!sr.EndOfStream) 
    { 
     var readLine = sr.ReadLine(); 
     if (readLine != null) 
     { 
      string[] strings = readLine.Split('-'); 
      using (SqlConnection sqlCon2 = new SqlConnection("REMOVED")) 
      { 
      using (SqlCommand sqlCmd2 = new SqlCommand { CommandText = "INSERT INTO [Products].[Features] ([ProductID] ,[Title] ,[ViewOrder]) VALUES ('" + strings[0] + "', '" + strings[1] + "', NULL) ", Connection = sqlCon2 }) 
      { 
       sqlCon2.Open(); 
       sqlCmd2.ExecuteNonQuery(); 
      } 
      } 
     } 
    } 
    } 
+0

这是类似于我需要的东西。我需要能够添加多个部分到文本框中,并插入它 –

+0

@ user3324892,但没有真正理解你的问题?什么文件和文本框的关系! – Akrem

+0

我认为OP是从文件加载到文本框中的数据? – gbianchi

0
List<string> _partNumbers = File.ReadLines(@"Text File Path").ToList(); 

List<string> _partNumbers = File.ReadAllLines(@"Text File Path").ToList(); 

遍历List_partNumbers,并把它们插入到数据库中。