如何更新主键设置为IsIdentity的数据?

时间:2013-02-07 23:01:42

标签: sql-server vb.net tsql

在以下代码中,命令执行但不会进行更新。主要问题是 IDNumber 的primary在SQL Server数据库中设置为 IsIdentity 。如果有人可以帮助我,我会感激不尽。

If rbnCore.Checked = True Then
                    subject = "Core"
                Else : subject = "Elective"
                End If
 qry = "Update ProgramDetails.Subjects set SubjectCode=@SubjectCode,SubjectName=@SubjectName,SubjectType=@SubjectType,UserID=@UserID,Password=@Password where IDNumber='" & txtIDNumber.Text & "'"
                cmd = New SqlCommand(qry, cn)
                cmd.Parameters.Add(New SqlParameter("@SubjectCode", txtSubjectCode.Text))
                cmd.Parameters.Add(New SqlParameter("@SubjectName", txtSubName.Text))
                cmd.Parameters.Add(New SqlParameter("@SubjectType", subject))
                cmd.Parameters.Add(New SqlParameter("@UserID", txtUserName.Text))
                cmd.Parameters.Add(New SqlParameter("@Password", txtPassword.Text))
                cmd.ExecuteNonQuery()
                MessageBox.Show("Record successfully updated", "Updated", MessageBoxButtons.OK, MessageBoxIcon.Information)
                showgrid()
            End If

2 个答案:

答案 0 :(得分:2)

首先,您绝对希望将IDNumber作为参数传入,以帮助防止SQL注入攻击(只需添加新参数并将代码更改为IDNumber = @ IDNumber)

通过检查cmd.ExecuteNonQuery()的结果,您可以轻松查看是否发生了更新 - 它返回受影响的行数,如果没有发生,显然会为零。

If rbnCore.Checked = True Then
                    subject = "Core"
                Else : subject = "Elective"
                End If
 qry = "Update ProgramDetails.Subjects set SubjectCode=@SubjectCode,SubjectName=@SubjectName,SubjectType=@SubjectType,UserID=@UserID,Password=@Password where IDNumber=@IDNumber"
                cmd = New SqlCommand(qry, cn)
                cmd.Parameters.Add(New SqlParameter("@IDNumber", txtIDNumber.Text))
                cmd.Parameters.Add(New SqlParameter("@SubjectCode", txtSubjectCode.Text))
                cmd.Parameters.Add(New SqlParameter("@SubjectName", txtSubName.Text))
                cmd.Parameters.Add(New SqlParameter("@SubjectType", subject))
                cmd.Parameters.Add(New SqlParameter("@UserID", txtUserName.Text))
                cmd.Parameters.Add(New SqlParameter("@Password", txtPassword.Text))
                If cmd.ExecuteNonQuery() > 0 Then
                  MessageBox.Show("Record successfully updated", "Updated", MessageBoxButtons.OK, MessageBoxIcon.Information)
                  showgrid()
                Else
                  'nothing affected...
                End If
            End If

答案 1 :(得分:0)

这是一个.Net环境吗?为什么你的字符串使用'&'用于连接而不是'+'。检查一下。因此,将您的查询重写为:  qry =“更新ProgramDetails.Subjects设置SubjectCode = @ SubjectCode,SubjectName = @ SubjectName,SubjectType = @ SubjectType,UserID = @ UserID,Pass word = @ Password其中IDNumber ='”+ txtIDNumber.Text +“'”