如何更新表vb.net中的特定列

时间:2019-01-23 10:13:01

标签: sql-server vb.net

我创建了一个数据库,它包含一个列名Cust_NColor。用户可以使用单击按钮时出现的“颜色”对话框为“名称”文本框选择颜色。我希望将选定的颜色值更新到Cust_NColor列中的数据库,并且还希望使用TableAdapterManager更新单个特定列,或者建议一种替代方法来更新特定列。

1 个答案:

答案 0 :(得分:0)

您可以尝试以下代码:

Dim cn As New SqlConnection()
Dim CustomersDataSet As New DataSet()
Dim da As SqlDataAdapter
Dim dr As DataRow        
Dim DAUpdateCmd As SqlCommand


cn.ConnectionString = "Server=.;Database=northwind;UID=sa;PWD=;"
cn.Open()

da = New SqlDataAdapter("select * from CustTest order by CustId", cn)

'Initialize the SqlCommand object that will be used as the DataAdapter's UpdateCommand.
'Note that the WHERE clause uses only the CustId field to locate the record that is to be updated.

DAUpdateCmd = New SqlCommand("Update CustTest set CustName = @pCustName where CustId = @pCustId", da.SelectCommand.Connection)


'Create and append the parameters for the Update command.

DAUpdateCmd.Parameters.Add(New SqlParameter("@pCustName", SqlDbType.VarChar))
DAUpdateCmd.Parameters("@pCustName").SourceVersion = DataRowVersion.Current
DAUpdateCmd.Parameters("@pCustName").SourceColumn = "CustName"

DAUpdateCmd.Parameters.Add(New SqlParameter("@pCustId", SqlDbType.Int))
DAUpdateCmd.Parameters("@pCustId").SourceVersion = DataRowVersion.Original
DAUpdateCmd.Parameters("@pCustId").SourceColumn = "CustId"


'Assign the SqlCommand to the UpdateCommand property of the SqlDataAdapter.
da.UpdateCommand = DAUpdateCmd        

da.Fill(CustomersDataSet, "Customers")        

Console.WriteLine("Customer Name before Update : " & CustomersDataSet.Tables("Customers").Rows(0)("CustName"))

CustomersDataSet.Tables("Customers").Rows(0)("CustName") = "Jack"
da.Update(CustomersDataSet, "Customers")        

Console.WriteLine("Customer Name updated successfully")

cn.Close()
Console.ReadLine()

您可以详细了解here