2012-11-14 57 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

相关问题