【问题标题】:Error show if there is a duplication of record in MySQL using vb.net错误显示使用 vb.net 在 MySQL 中是否存在重复记录
【发布时间】:2021-03-25 02:08:27
【问题描述】:

美好的一天!有人可以帮我修复我的代码吗?如果有重复记录,我想显示一条错误消息。例如,我输入了一个用户名“admin”,但它已经在我的数据库中,所以它应该显示一条消息“用户名已经存在!”。否则,如果尚未使用用户名,那么它将被添加到我的数据库中。我正在使用 Visual Studio 2005 和 Navicat for MySQL 这是我的代码:

conn.Open()

        Dim qadd As String = "SELECT * FROM tbl_user WHERE uname='" & txt_uname.Text & "'"
        Dim cmd As New MySqlCommand(qadd, conn)
        Dim data As MySqlDataReader = cmd.ExecuteReader

        If data.Read Then
            If data(0) = txt_uname.Text Then
                MsgBox("User " & data(0) & " already exists! ", MsgBoxStyle.Critical)
            Else
                Dim qstr As String = "INSERT INTO tbl_user (uname, pword, ulvl) VALUES ('" & txt_uname.Text & "' , '" & txt_pword1.Text & "' , '" & txt_pword2.Text & "') ON DUPLICATE KEY UPDATE uname = '" & txt_uname.Text & "'"
                Dim cm As New MySqlCommand(qstr, conn)
                Dim dat As MySqlDataReader = cm.ExecuteReader
                MsgBox("User has been added!", MsgBoxStyle.Information)
                txt_uname.Clear()
                txt_pword1.Clear()
                txt_pword2.Clear()
                txt_uname.Focus()
            End If
        End If

        conn.Close()

【问题讨论】:

  • 对此有几种不同的方法。你已经在做一个,所以不太确定问题是什么。第二种选择是在数据库中创建一个唯一索引,当尝试插入可以根据需要捕获和处理的重复记录时,这将导致异常。
  • 另外,阅读参数化你的 sql 命令。比您当前拥有的字符串连接更容易使用
  • 我的代码有效,当我在我的数据库中已经存在的注册表单中输入用户名时,它说用户名已经存在。但是我的问题是当我尝试输入一个在我的数据库中没有记录的新用户名时,它什么也没做。
  • 啊,明白了。更改您的查询以计算用户代码 = txt_uname.text 的用户记录。然后使用 executescaler 返回匹配记录的数量。 if 0 insert, else 消息
  • 这就像 if 语句只有效而 Else 语句无效

标签: mysql vb.net navicat


【解决方案1】:

还有很大的改进空间,我在手机上输入了这个,没有进行语法检查,但我认为它应该能让你朝着正确的方向前进。您需要阅读的内容是参数化您的查询/插入语句和 Using 关键字,这有助于管理您的数据库连接。

Dim qadd As String = "SELECT Count(uname)  FROM tbl_user WHERE uname='" & txt_uname.Text & "'"
Dim cmd As New MySqlCommand(qadd, conn)
Dim userCounter as int = cmd.ExecuteScaler
if userCounter > 0 then
  MsgBox("User " & data(0) & " already exists! ", MsgBoxStyle.Critical)
Else
  Dim qstr As String = "INSERT INTO tbl_user (uname, pword, ulvl) VALUES ('" & txt_uname.Text & "' , '" & txt_pword1.Text & "' , '" & txt_pword2.Text & "') ON DUPLICATE KEY UPDATE uname = '" & txt_uname.Text & "'"
  Dim cm As New MySqlCommand(qstr, conn)
  Dim dat As MySqlDataReader = cm.ExecuteReader
  MsgBox("User has been added!", MsgBoxStyle.Information)
  txt_uname.Clear()
  txt_pword1.Clear()
  txt_pword2.Clear()
  txt_uname.Focus()
End If

【讨论】:

  • 我已经尝试了您的代码并且它可以工作,但是当我尝试添加新用户时,它说“已经有一个打开的 DataReader 与此连接关联,必须先关闭它。”在这部分“Dim dat As MySqlDataReader = cm.ExecuteReader”
  • 嗯,这个例外很明显。您在代码中的某处留下了打开的数据连接。这又回到了通过 Using 子句来实现你的连接,这将为你解决所有问题
  • 太棒了,真的很想说明一下,这段代码有一些严重的缺陷,你应该先解决这些缺陷,然后再进一步
猜你喜欢
  • 2011-08-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-09-22
  • 1970-01-01
  • 1970-01-01
  • 2013-01-03
相关资源
最近更新 更多