2017-01-26 5 views
-2

I need to insert the data into a SQl database using SSIS or C#. Could somebody provide some help to transform the data into a SQL table. Please CLICK HERE to see the current data layout and the desired resultПреобразование данных из текстового файла в SQL:

+0

Пожалуйста, нажмите на синий текст, чтобы увидеть текущие данные и нужное состояние – Carlos

+5

Пожалуйста, нажмите на этот синий текст [ask], чтобы узнать о том, как задавать вопросы, а также thi s one [Tour] – Plutonix

ответ

0

Вы попросили нас предоставить вам код. Ты даже не пытался.

Используйте filereader, добавьте каждую строку в строку. Добавьте строку в свою базу данных с помощью execcescalar или ExecuteNonquery или что-то в этом роде.

Если вы предоставили нам код, вам будет легче помочь. Прямо сейчас я ничего не могу сделать. Google, которые я вам сказал, и вы найдете достаточно тем с тем же вопросом.

0

Эти два решения я пытался

Решение 1:

//Create Connection to SQL Server 
SqlConnection SQLConnection = new SqlConnection(); 
SQLConnection.ConnectionString = "Data Source = (local); Initial Catalog =TechBrothersIT; " + "Integrated Security=true;"; 

System.IO.StreamReader SourceFile = new System.IO.StreamReader(SourceFolder+SourceFileName); 

string line = ""; 
Int32 counter = 0; 

SQLConnection.Open(); 

while ((line = SourceFile.ReadLine()) != null) 
{ 
    //skip the header row 
    if (counter > 0) 
    { 
     //prepare insert query 
     string query = "Insert into " + TableName + 
         " Values ('" + line.Replace(filedelimiter, "','") + "')"; 

     //execute sqlcommand to insert record 
     SqlCommand myCommand = new SqlCommand(query, SQLConnection); 
     myCommand.ExecuteNonQuery(); 
    } 

    counter++; 
} 

SourceFile.Close(); 
SQLConnection.Close(); 

//Move the file to Archive folder 
File.Move(SourceFolder+SourceFileName, ArchiveFodler + SourceFileName);    

Решение 2:

Первоначально я решил это с запросом Excel:

Sub Transpone() 
a = 1 
    `enter code here` b = 8 
    Do ' Bucle externo. 
    Do While Contador < 65000 
     Contador = Contador + 1 
     If Range("A" & a) <> "" Then 
    Range("A" & a & ":A" & b).Select 
    Selection.Copy 
    Sheets("Converted").Select 
    k = Range("A" & Cells.Rows.Count).End(xlUp).Row + 1 
    `enter code here`Range("A" & k).Select 
    `enter code here`Selection.PasteSpecial Paste:=xlPasteAll, Operation:=xlNone, SkipBlanks:= _ 
     False, Transpose:=True 
    Sheets("Identification").Select 
    a = a + 8 
    b = b + 8 
     Else 
    Comprobar = False 
     Exit Do 
     End If 
     Loop 
    Loop Until Comprobar = False 
End Sub 
+1

[SQL Injection alert] (http://msdn.microsoft.com/en-us/library/ms161953%28v=sql.105%29.aspx) - вы должны ** не ** объединиться вместе ваши SQL-операторы - используйте ** параметризованные запросы ** вместо этого, чтобы избежать SQL-инъекции. –

0

It может быть очень легко выполнена в SSIS. Эта ссылка может помочь вам.

https://blogs.msdn.microsoft.com/philoj/2007/11/10/transposing-rows-and-columns-in-sql-server-integration-services/

+0

Я использую этот скрипт для повторения строк из текстового файла. Это позволяет мне читать группы по 6 рядов каждый раз. – Carlos

0

Я использую задачу SSIS-скрипт, чтобы читать строки из текстового файла. Это позволяет мне читать группы по 6 строк в каждом цикле. Переменные переносятся в задачу SQL, содержащую вставку. Мне нужна помощь, так как она вставляет все текстовые строки в ту же строку SQL, что не добавляется, ниже вы увидите вкладку insert.

общественности недействительным Main() {

 SqlConnection conn = new SqlConnection("Data Source=DESKTOP-QBDQ35H; Initial Catalog=TensorFacts; Integrated Security=True"); 
     int counter = 0; 

     System.IO.StreamReader file = new System.IO.StreamReader("C:\\Imagine processing\\output.txt"); 
     string[] large = System.IO.File.ReadAllLines("C:\\Imagine processing\\output.txt"); 
     for (int i = 0; i < large.Length; i += 6) 

     { 

      Dts.Variables["User::imageName"].Value = (string)large[i]; 
      Dts.Variables["User::bestGuess"].Value = (string)large[i + 1]; 
      Dts.Variables["User::secondGuess"].Value = (string)large[i + 2]; 
      Dts.Variables["User::thirdGuess"].Value = (string)large[i + 3]; 
      Dts.Variables["User::fourthGuess"].Value = (string)large[i + 4]; 
      Dts.Variables["User::fifthGuess"].Value = (string)large[i + 5]; 

      //string line0 = large[i]; 
      //string line1 = large[i + 1]; 
      //string line2 = large[i + 2]; 
      //string line3 = large[i + 3]; 
      //string line4 = large[i + 4]; 
      //string line5 = large[i + 5]; 


      //MessageBox.Show(line0 + '\n' + line1 + '\n' + line2 + '\n' + line3 + '\n' + line4 + '\n' + line5 + '\n'); 

      //counter++; 
     } 
    } 

ТОГДА В SSIS "ВЫПОЛНИТЬ SQL Такс" INSERT INTO dbo.scores (ImageName, bestGuess, firstScore, firsTag, secondGuess, secondScore, secondTag, thirdGuess, thirdScore , thirdTag, 4thGuess, 4thScore, 4thTag, 5thGuess, 5thScore, 5thTag) ЦЕННОСТИ (?,?, 0,0,?, 0,0,?, 0,0,?, 0,0,?, 0,0)