使用强类型DataSet更新ASP.Net/VB.Net数据库

Ema*_*een 1 vb.net asp.net dataset strongly-typed-dataset tableadapter

我们希望使用通过更改ASP.Net上的值获得的值来更新SQL Server 2012数据库中的数据DetailsView.我想使用更新数据库

  • 一个强类型的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
Run Code Online (Sandbox Code Playgroud)

我确信之前曾多次询问过这个问题,但我找不到如何使用查询的好例子:StrSqlStatement通过强类型DataSet更新数据库.

Sea*_*rey 5

首先,您需要一个连接字符串,最好将连接字符串存储在web.config文件中:

<connectionStrings>
  <add name="MyConnectionString" connectionString="Data Source=putYourServerAndInstanceNameHere;Initial Catalog=putYourDatabaseNameHere;User ID=putYourSqlUsernameHere;Password=password" providerName="System.Data.SqlClient" />
</connectionStrings>
Run Code Online (Sandbox Code Playgroud)

这是根<configuration>元素的直接子元素.有关连接字符串的更多信息,请访问http://www.connectionstrings.com.

然后你需要在你的代码隐藏中进行一些导入,如果你还没有它们,你需要将它们作为项目的引用添加:

Import System.Data
Import System.Data.SqlClient
Run Code Online (Sandbox Code Playgroud)

然后我们连接到数据库并运行我们的命令,我们使用参数因为它们更安全.

'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
Run Code Online (Sandbox Code Playgroud)

请注意,这里不需要使用conn.Close(),因为Using语句将为您处理(SqlConnection的Dispose方法在它仍处于打开状态时关闭连接).