如何更新自动生成主键的数据

时间:2011-12-20 21:49:36

标签: sql vb.net

表的主键是使用Is Identity自动生成的,我想根据主键更新。以下代码肯定有问题,所以我希望有人为我修改它。提前谢谢。

     Try
        Dim qry As String
        qry = "Update StudentDetails.Programmes set Programme=@Programme,Form=@Form,AcademicYear=@AcademicYear,Class=@Class where ID=ID"
            cmd = New SqlCommand(qry, cn)
            cmd.Parameters.Add(New SqlParameter("@Programme", txtProgramme.Text))
            cmd.Parameters.Add(New SqlParameter("@Form", txtForm.Text))
            cmd.Parameters.Add(New SqlParameter("@AcademicYear", txtAcademicYear.Text))
            cmd.Parameters.Add(New SqlParameter("@Class", txtClass.Text))
            cmd.ExecuteNonQuery()
            MessageBox.Show("Record succesfully updated", "Updated", MessageBoxButtons.OK, MessageBoxIcon.Information)
            showgrid()
        End If
        txtProgramme.Focus()
    Catch ex As Exception
    End Try

'PS:下面的代码显示了如何插入数据。在数据库中是否将“身份”设置为“是”。工作完美。我要纠正的代码问题是上面的更新命令。

 Private Sub btnSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSave.Click
    Try
        cmd = New SqlCommand("Insert into StudentDetails.programmes(Programme,Form,AcademicYear,Class) values(@Programme,@Form,@AcademicYear,@Class)", cn)

        cmd.Parameters.AddWithValue("@Programme", txtProgramme.Text)
        cmd.Parameters.AddWithValue("@Form", txtForm.Text)
        cmd.Parameters.AddWithValue("@AcademicYear", txtAcademicYear.Text)
        cmd.Parameters.AddWithValue("@Class", txtClass.Text)
        cmd.ExecuteNonQuery()
        MessageBox.Show("Record successfully saved", "Saved", MessageBoxButtons.OK, MessageBoxIcon.Information)

2 个答案:

答案 0 :(得分:2)

以下是有关如何使用ADO.NET检索新标识值的不言自明的示例:

Using con = New SqlConnection(My.Settings.CC_ConnectionString)
    Dim newID As Int32
    Using insertCommand = New SqlCommand("INSERT INTO Test(Value)VALUES(@Value);SELECT CAST(scope_identity() AS int)", con)
        insertCommand.Parameters.AddWithValue("@Value", "Value1")
        con.Open()
        newID = DirectCast(insertCommand.ExecuteScalar, Int32)
    End Using

    If newID <> 0 Then
        Using updateCommand = New SqlCommand("UPDATE TEST SET Value='Value1.1' WHERE idTest=@idTest", con)
            updateCommand.Parameters.AddWithValue("@idTest", newID)
            If con.State <> ConnectionState.Open Then con.Open()
            Dim updatedRecordCount = updateCommand.ExecuteNonQuery
        End Using
    End If
End Using

两个重要部分是:

SELECT CAST(scope_identity() AS int)

将返回新的标识值

DirectCast(insertCommand.ExecuteScalar, Int32)
如果插入了新行,

将返回新的Identity列值,失败时返回0。

使用参数会阻止SQL-Injection

答案 1 :(得分:0)

您没有告诉它要匹配的ID。

&安培; “'ID = ID”

&安培; “'ID ='”&amp; txtID.Text&amp; “'”

并遵循蒂姆的建议。