更新不存储在数据库中的值

时间:2013-08-25 19:38:00

标签: database vb.net dataset

代码在没有ERRoR的情况下工作但更新值不存储在数据库中 ??? 它是更新数据库值的正确方法???

Try

        da = New SqlDataAdapter("SELECT * FROM studentdetails where student_id= @id", myConn)
        da.SelectCommand.Parameters.AddWithValue("@id", txt_id.Text)
        da.Fill(dset, "studentdetails")

        If dset.Tables("studentdetails").Rows(0)("student_id") = Convert.ToInt32(txt_id.Text) Then
            dset.Tables("studentdetails").Rows(0)("student_name") = txt_name.Text
            dset.Tables("studentdetails").Rows(0)("student_branch") = txt_branch.Text
            dset.Tables("studentdetails").Rows(0)("student_class") = txt_class.Text
            MsgBox("Update Complete")
        Else
            MsgBox("Record not found")
        End If

    Catch ex As Exception
        MsgBox(ex.Message)
    Finally

        myConn.Close()
    End Try

2 个答案:

答案 0 :(得分:2)

首先,如果要更新记录,则无需选择记录。因此我会使用SqlCommand和相应的update-sql。然后使用它的ExecuteNonQuery方法。

其次,由于您要将ID转换为Int32,我假设数据库中列的类型也是int。但是您将string参数传递给SelectCommand的{​​{1}}。请注意DataAdapter尝试从值中推断出类型,因此您应该提供正确的类型。

但是,如果您想使用AddWithValue更新记录,则必须提供SqlDataAdapter。然后,当您致电UpdateCommand时,DataTable / DataSet中的所有更改都将写入数据库。

以下是一个示例(同样,由于您可以直接使用DataAdapter.Update更新,因此选择是多余且效率低下的):

SqlCommand.ExecuteNonQuery

答案 1 :(得分:1)

要在数据库中存储某些内容,您需要一个像这样的INSERT命令

Dim cmdInsert = "INSERT INTO studentdetails (student_id, student_name, " & _
                "student_branch, student_class) VALUES " & _
                "(@id, @name, @branch, @class)"
Dim cmd = new SqlCommand(cmdInsert,myConn) 
cmd.Parameters.AddWithValue("@id",Convert.ToInt32(txt_id.Text)(
cmd.Parameters.AddWithValue("@name", txt_name.Text)
cmd.Parameters.AddWithValue("@branch", txt_branch.Text)
cmd.Parameters.AddWithValue("@class", txt_class.Text)
Dim rowsInserted = cmd.ExecuteNonQuery()
if rowsInserted = 1 Then
   MsgBox("Record inserted")
Else
   MsgBox("Error inserting Record")
End If

当然,这会尝试在数据库中插入新记录。要更新现有记录,您需要UPDATE命令。或许最好在various SQL commands

进行快速审核
相关问题