2012-11-14 61 views
1

我們希望更新SQL Server 2012數據庫中的數據,其中值從 更改爲ASP.Net DetailsView上的值。我會想更新使用使用強類型數據集更新ASP.Net/VB.Net數據庫

  • 數據庫中的一個強類型DataSet稱爲DataSetParentsDetails
  • 一個TableAdapter稱爲ParentsDetailsTableAdapter
  • 一個DataTable名爲ParentsDetails

這些是使用DataSet Designer創建的。

這是從代碼的代碼隱藏用於弄清楚我們要更新到數據庫中的文件數量:

Protected Sub DetailsViewDetails_ItemCommand(sender As Object, e As System.Web.UI.WebControls.DetailsViewCommandEventArgs) 
    Dim dcmAmountToAdjust As Decimal 
    Dim StrSqlStatement As String 

    Select Case e.CommandName 
    Case "Add" 
    Case "Edit" 
     dcmOriginalRegistrationFee = GetValueFromLabelRegistrationFee() 
    Case "Delete" 
    Case "Update" 
     dcmNewRegistrationFee = GetValueFromTextBoxRegistrationFee() 
     dcmAmountToAdjust = dcmNewRegistrationFee - dcmOriginalRegistrationFee 
     ' Update the tuition balance in the parent's data. 
     '------------------------------------------------- 
     StrSqlStatement = 
     "Update Students " & _ 
     "Set RegistrationCode = RegistrationCode + @AmountToAdjust " & _ 
     "Where StudentID = @ID" 
     ' Code to update the database goes here. 
     '--------------------------------------- 
    End Select 
End Sub 

我敢肯定,這是問過很多次,但我可以」 t找到一個很好的例子來說明如何使用StrSqlStatement中的查詢來通過強類型的DataSet更新數據庫。

+0

我在這裏丟失了一點,還是會使用標準的SqlConnection和SqlCommand來完成這項工作?您可以傳入參數並指定數據類型,大小以及所需的所有內容。 – Sean

+0

感謝您的回覆。是的,如果這是更新數據庫的最簡單方法。請你可以展示一個編碼樣本?謝謝。 –

回答

4

首先你需要一個連接字符串,它是很好的做法,存儲在web.config文件的連接字符串:

<connectionStrings> 
    <add name="MyConnectionString" connectionString="Data Source=putYourServerAndInstanceNameHere;Initial Catalog=putYourDatabaseNameHere;User ID=putYourSqlUsernameHere;Password=password" providerName="System.Data.SqlClient" /> 
</connectionStrings> 

這根<configuration>元素的直接孩子。有關連接字符串的更多信息,請訪問http://www.connectionstrings.com

然後,你需要在你的部分進口代碼隱藏,並且你需要他們作爲引用添加到您的項目,如果你還沒有在那裏得到了他們:

Import System.Data 
Import System.Data.SqlClient 

然後我們連接到數據庫並運行我們的命令,我們使用參數,因爲它們更安全。

'build the connection object using the string from the web.config file 
Using conn As New SqlConnection(ConfigurationManager.ConnectionStrings("MyConnectionString").ConnectionString) 
    'build the command object specifying the command text and the connection to use, conn 
    Using cmd As New SqlCommand("UPDATE Students SET RegistrationCode = RegistrationCode + @AmountToAdjust WHERE StudentID = @ID", conn) 
    'add the parameters needed by the command 
    cmd.Parameters.AddWithValue("@AmountToAdjust", amountToAdjust) 
    cmd.Parameters.AddWithValue("@ID", studentID) 
    'try to open the connection and execute the statement 
    Try 
     conn.Open() 
     cmd.ExecuteNonQuery() 
    Catch ex As Exception 
     'handle the exception here 
    End Try 
    End Using 
End Using 

請注意,有沒有必要使用conn.Close()這裏作爲Using聲明會照顧的,對你(的SqlConnection的Dispose方法關閉連接,如果它仍處於打開狀態)。

+0

肖恩,你是如此的樂於助人!非常感謝您提供非常詳細的幫助。每個人,請給這個傢伙很多「這個答案很有用」的票。 :-) –

+0

非常歡迎=] – Sean