2016-02-05 43 views
1

我正在研究從微軟的SqlParameter example,我試圖瞭解:爲什麼sqlParameter請求sourceColumn?

什麼是指定SourceColumn的原因和好處?

SQL命令已經指定目標列。

command = New SqlCommand(_ 
     "INSERT INTO Customers (CustomerID, CompanyName) " & _ 
     "VALUES (@CustomerID, @CompanyName)", connection) 

    command.Parameters.Add("@CustomerID", SqlDbType.NChar, 5, "CustomerID") 
    command.Parameters.Add("@CompanyName", SqlDbType.NVarChar, 40, "CompanyName") 

enter image description here

+0

我不明白的問題。該適配器必須知道爲了設置值而使用哪個列。 –

+0

@Aツ:imo這是一個公平的問題。雖然我使用ADO.NET 14年 –

+0

@Aツ在上面的例子中的INSERT語句提供了源專欄中,我從來沒有使用這個屬性。 「 – Obsidian

回答

1

指定在該實例中SourceColumn裝置在DataTableDataset指定列名屬性(DataColumn.ColumnName)。

--first, fill a DataTable with data from the database: 
Dim dt As New DataTable 
Dim cmdSelect = New SqlCommand("SELECT CustomerID, CompanyName FROM Customers;", connection) 
Dim daCustomers As New SqlDataAdapter 
daCustomers.SelectCommand = cmdSelect 
daCustomers.Fill(dt) 

--Now our DataTable has two columns: "CustomerID" and "CompanyName" 
--We can help out our DataAdapter by telling it which columns in the database 
--correspond with which columns in the DataTable 
--which is what you've done with your fourth argument of .Parameters.Add() 
command = New SqlCommand(_ 
    "INSERT INTO Customers (CustomerID, CompanyName) " & _ 
    "VALUES (@CustomerID, @CompanyName)", connection) 

command.Parameters.Add("@CustomerID", SqlDbType.NChar, 5, "CustomerID") 
command.Parameters.Add("@CompanyName", SqlDbType.NVarChar, 40, "CompanyName") 
daCustomers.InsertCommand = command 

如果我們這樣來做的話,我們將不會有永遠指定兩個參數的值(:當您使用的是SqlDataAdapter對象連同您的SqlCommand像這樣這是唯一重要的在這種情況下,InsertCommand火災時),因爲數據適配器將光看數值在適當DataColumn & DataRow時自動調用daCustomers.Update(dt)

同樣的,如果你希望你的SqlDataAdapter會更加有用,你想也指定SourceColumn爲您定義UpdateCommandDeleteCommand S的參數。需要注意的是,很多人喜歡使用SqlCommandBuilderobject to automatically configure他們SqlDataAdapters這和其他簡單的適配器不指定任何東西他們SqlCommand對象,但我更喜歡什麼,但最簡單的情況下,這更明確的辦法。

我不知道有什麼好處通過指定SourceColumn當你不使用一個SqlDataAdapterSqlCommand獲得。