2017-06-06 219 views
-2
conn.Open(); 
string query = "INSERT INTO Film (Film, Jaartal, Cijfer) VALUES ('" + filmnaam + "','" + jaartal + "','" + cijfer + "')"; 
string LastID = "SELECT TOP 1 Id FROM Film ORDER BY Id DESC"; 




SqlCommand cmd = new SqlCommand(query, conn); 
SqlCommand cmd2 = new SqlCommand(LastID, conn); 
cmd.ExecuteNonQuery(); 

using (SqlDataReader dr = cmd2.ExecuteReader()) 
{ 

    while (dr.Read()) 
    { 
      string ID = dr["Id"].ToString(); 
      string add= "INSERT INTO GenreFilm (FilmId) VALUES ('" + ID + "')"; 
      SqlCommand cmd3 = new SqlCommand(add, conn); 
      cmd3.ExecuteNonQuery(); 


    } 
} 

我想將我的(LastID)查詢的值(ID)添加到我的數據庫表中。但我似乎無法做到這一點。以上是我現有的代碼。任何幫助/提示將不勝感激!如何從SQL查詢中獲取值?

+0

請添加語言標記 – Jens

+6

您不應該通過重新查詢來檢索新ID,由於多種原因這是不安全的。數據庫提供了一種機制讓你獲得價值,告訴我們你的數據庫,我們會告訴你它是什麼。 –

+0

https://stackoverflow.com/questions/7917695/sql-server-return-value-after-insert –

回答

1

並不直接提供解決方案而是跟隨牢記什麼@ADyson表示有關參數(SQL注入),什麼@Dimitry表示關於允許數據庫獲取的價值爲你流。希望這會有所幫助。

該代碼有評論灑在裏面。第一類DemoForOperations展示瞭如何在第二類操作中調用該方法。當然你可以在任何你想要的操作中調用insert方法。

using System; 
using System.Data.SqlClient; 

namespace StackOverFlowSample 
{ 
    public class DemoForOperations 
    { 
     public void TheDemo() 
     { 
      var ops = new Operations(); 
      var firstName = "Karen"; 
      var lastName = "Payne"; 
      var returningNewId = 0; 
      if (ops.SampleInsert(firstName,lastName,ref returningNewId)) 
      { 
       // success, returningNewId has the new key value which can be 
       // used for whatever you want e.g. as a value for another query. 
      } 
      else 
      { 
       // failed, you can use the following the 
       // figure out the issue 
       var exceptionMessage = ops.Exception.Message; 
      } 

     } 
    } 
    public class Operations 
    { 
     private Exception exception; 
     public Exception Exception { get { return exception; } } 
     /// <summary> 
     /// Insert a record 
     /// </summary> 
     /// <param name="FirstName"></param> 
     /// <param name="LastName"></param> 
     /// <param name="NewIdentifier"> 
     /// pass in a valid int by ref 
     /// </param> 
     /// <returns> 
     /// true if successful, false otherwise and will set the property 
     /// Exception so that the caller can see what went wrong 
     /// </returns> 
     public bool SampleInsert(string FirstName, string LastName, ref int NewIdentifier) 
     { 
      // here we create the connection new but of course a connection can be created 
      // outside of the method that is in-scope of this method 
      using (SqlConnection cn = new SqlConnection() { ConnectionString = "TODO" }) 
      { 
       // setup for insert using parameters 
       // along with a secondary query to return the new primary key value 
       var statement = "INSERT INTO Contacts (FirstName,LastName) " + 
           "VALUES (@FirstName,@LastName); " + 
           "SELECT CAST(scope_identity() AS int);"; 

       using (SqlCommand cmd = new SqlCommand()) 
       { 
        cmd.Connection = cn; 
        cmd.CommandText = statement; 

        try 
        { 
         // setup our parameters 
         cmd.Parameters.AddWithValue("@FirstName", FirstName); 
         cmd.Parameters.AddWithValue("@LastName", LastName); 

         cn.Open(); 

         // get new primary key 
         NewIdentifier = Convert.ToInt32(cmd.ExecuteScalar()); 

         return true; 

        } 
        catch (Exception ex) 
        { 
         exception = ex; 
         return false; 
        } 
       } 
      } 
     } 
    } 
}