+ -
当前位置:首页 → 问答吧 → 求大师看一下这一段update代码

求大师看一下这一段update代码

时间:2011-12-18

来源:互联网

Function pass(ByVal Aid As String, ByVal 旧密码 As String, ByVal 新密码 As String, ByVal 确认新密码 As String) As Integer
  mycon.Open()
  mycmd.Connection = mycon
  mycmd.CommandText = "select * from Admin where Aid='" & Aid & "' and password='" & 旧密码 & "'"
  reader = mycmd.ExecuteReader()
  If reader.Read = False Then '若无返回记录
  Return 0
  ElseIf 新密码 = 确认新密码 Then
  mycmd.CommandText = "update Admin set password='" & 新密码 & "' where Aid='" & Aid & "'"
  mycmd.ExecuteNonQuery()
  mycon.Close()
  Return 1
  Else
  Return 0
  End If
  End Function

第一步的检查旧密码有用,但是第二个更新密码就不行了…

作者: seventhsin   发布时间: 2011-12-18

要先把 reader 关掉才能执行新的命令

作者: orain   发布时间: 2011-12-18

引用 1 楼 orain 的回复:

要先把 reader 关掉才能执行新的命令

  ElseIf 新密码 = 确认新密码 Then
  reader.Close()
  mycmd.CommandText = "update Admin set password='" & 新密码 & "' where Aid='" & Aid & "'"
改成这样还是一样的错误…

作者: seventhsin   发布时间: 2011-12-18

这个代码大致是这样写的:VB.NET code
Imports System.Data.Common

Public Class Class1

    Shared connStr As String

    Sub pass(ByVal Aid As String, ByVal 旧密码 As String, ByVal 新密码 As String, ByVal 确认新密码 As String)
        Using mycon As New SqlClient.SqlConnection(connStr)
            mycon.Open()
            Dim mycmd As DbCommand = mycon.CreateCommand()
            mycmd.CommandText = "select * from Admin where Aid='" & Aid & "' and password='" & 旧密码 & "'"
            Dim reader As DbDataReader = mycmd.ExecuteReader()
            If reader.Read = False Then Throw New Exception("没有记录。")

            If 新密码 = 确认新密码 Then
                mycmd.CommandText = "update Admin set password='" & 新密码 & "' where Aid='" & Aid & "'"
                mycmd.ExecuteNonQuery()
            Else
                Throw New Exception("密码错误。")
            End If
        End Using
    End Sub
End Class

其中最为关键地是每一次都要new一个新的DbConnection对象出来,这样才不至于因为共享mycon而悲剧地崩溃。

作者: sp1234   发布时间: 2011-12-18

哦,上面的代码还是比较差劲,拼接sql字符串时要处理Aid和“旧密码”中的单引号,也就是应该为:[code=VB.NETmycmd.CommandText] = "select * from Admin where Aid='" & Aid.Replace("'", "''") & "' and password='" & 旧密码.Replace("'", "''") & "'"[/code]

作者: sp1234   发布时间: 2011-12-18

VB.NET code
mycmd.CommandText = "select * from Admin where Aid='" & Aid.Replace("'", "''") & "' and password='" & 旧密码.Replace("'", "''") & "'"

作者: sp1234   发布时间: 2011-12-18