2012-07-01 77 views
1

enter image description here結合表,插入,然後選擇

我學習這個我自己,我已經到了一個地步,我想插入新的類別和新的國家,但我不知道該怎麼做究竟。

如用於增加一個新的類別我做到以下幾點:

public int Insert() 
{ 
    string sqlString = "INSERT INTO Categories (name, image) VALUES (@Name, @Image);"; 
    SqlConnection sqlConnection = new 
     SqlConnection(ConfigurationManager.ConnectionStrings["OahuDB"].ConnectionString); 
    SqlCommand sqlCommand = new SqlCommand(sqlString, sqlConnection); 
    sqlCommand.Parameters.AddWithValue("@Name", this.Name); 
    sqlCommand.Parameters.AddWithValue("@Image", this.Image); 
    sqlConnection.Open(); 
    int x = sqlCommand.ExecuteNonQuery(); 
    sqlConnection.Close(); 
    sqlConnection.Dispose(); 
    return x; 
} 

但是我應該如何同時插入表之間的關係,然後檢索基於聯結表中的數據?

如果你可以給這個例子和好的教程,或者你可以詳細說明一下。 非常感謝。

+0

爲什麼不使用存儲過程並通過C#調用它。 [這裏](http://stackoverflow.com/questions/5762942/stored-procedure-to-insert-two-tables-with-relationship)就是一個例子,要了解更多關於聯結表的信息,請參考[this](http ://megocode3.wordpress.com/2008/01/04/understanding-a-sql-junction-table/) –

回答

1

發送SQL這樣的:

INSERT INTO Categories (name, image) VALUES (@Name, @Image); 
SELECT scope_identity() as NewCategoryId; 

這將返回新添加的類別的ID作爲行集。您可以使用來獲取新的ID熟悉ExecuteReader()

using (var read = sqlCommand.ExecuteReader()) 
{ 
    read.Read(); 
    int newCategoryId = (int) read["NewCategoryId"]; 
} 

或甚至ExecuteScalar()短:

int newId = (int)sqlCommand.ExecuteScalar(); 

順便說一下,考慮包裹在using的連接:

using (var sqlConnection = new SqlConnection("...connection string...") 
{ 
    sqlConnection.Open(); 
    var sqlCommand = sqlConnection.CreateCommand(); 
    ... 
} 

這有助於防止連接泄漏。無論是超時還是網絡問題,其中一個Execute方法總是有可能拋出異常。

+0

那麼檢索完id後我會再次插入到聯結表中? – user1027620

+0

是的,如果你需要一個新的國家,當然你必須先插入 – Andomar

相關問題