2015-11-27 65 views
0

如何從第一個查詢中查找ID並返回該值,以便將其插入到query2中?這是用戶在前端完成表單時需要完成的代碼。我需要填充兩個表,它們將通過ID「StoryID」關聯起來,這是一個自動創建的主鍵。使用ExecuteReader返回主鍵

protected void Upload2_Click(object sender, EventArgs e) 
{  
     userStoryForm.Visible = false; 
     info.Text = "You have successfully added a new user story."; 


     String connectionString = WebConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString; 


     String usernameData = username.Text.ToString(); 
     int captureProjectID = Convert.ToInt32(Request.QueryString.Get("ProjectID")); 
     String storyno = StoryNoTextBox.Text; 
     String userstory = StoryTextTextBox.Text; 

     //Create connection 
     SqlConnection myConnection = new SqlConnection(connectionString); 

     //open connection 
     myConnection.Open(); 

     String query = "INSERT INTO UserStories (StoryNo, StoryText, ProductOwner, ProjectID) " + 
         "VALUES ('" + storyno + "','" + userstory + "','" + usernameData + "','" + captureProjectID + "')" + 
         "SELECT SCOPE_IDENTITY() AS StoryID;"; 

     SqlCommand myCommand = new SqlCommand(query, myConnection); 

     // Call GetOrdinal and assign value to variable. 
     SqlDataReader reader = myCommand.ExecuteReader(); 

     int StoryIDData = reader.GetOrdinal("StoryID"); 

     // Use variable with GetString inside of loop. 
     while (reader.Read()) 
     { 
      Console.WriteLine("StoryID={0}", reader.GetString(StoryIDData)); 
     } 

     // Call Close when done reading. 
     reader.Close(); 

     //insert productowner, projectID and storyID into ProductBacklog table 
     String query2 = "INSERT INTO ProductBacklog (ProductOwner, ProjectID, StoryID) VALUES ('" + usernameData + "', @returnProjectID,'" + StoryIDData + "')"; 
     SqlCommand myCommand2 = new SqlCommand(query2, myConnection); 
     myCommand2.Parameters.AddWithValue("@returnProjectID", captureProjectID); 


     //close connection 
     myConnection.Close(); 

    } 

} 
+0

INSERT INTO ... OUTPUT Inserted.StoryID VALUES ...'MS SQL –

回答

2

最重要的是 - 在你的SQL命令中使用參數。永遠不要連接那樣的字符串。您要求提供SQL injection攻擊。

string query = @" 
    INSERT INTO UserStories (StoryNo, StoryText, ProductOwner, ProjectID) 
    VALUES (@storyno, @userstory, @usernameData, @captureProjectID) 
    SELECT CAST(SCOPE_IDENTITY() AS INT)"; 

SqlCommand myCommand = new SqlCommand(query); 
myCommand.Parameters.Add("@storyno", DbType.String).Value = storyno; 
... 

去得到返回的ID,使用ExecuteScalar()

int StoryIDData = (int)myCommand.ExecuteScalar(); 

而且,你不正確地處理你的資源。如果該方法拋出異常,則不會關閉SQLConnection。你應該把它放在using聲明中。

+0

感謝您的迴應!我仍然有點困惑。我可以刪除整個executeReader部分嗎? – Colette

+0

@Colette是的,只需執行'ExecuteScalar()'就可以執行命令並獲取單個值。 –

+0

非常感謝你!現在它終於工作了:D – Colette