简体   繁体   English

错误显示使用 vb.net 在 MySQL 中是否存在重复记录

[英]Error show if there is a duplication of record in MySQL using vb.net

Good day?再会? Can someone help me fix my code.有人可以帮我修复我的代码。 I would like to show an error message if there is a duplication of record, For example.例如,如果存在重复记录,我想显示一条错误消息。 I entered a username "admin" but it is already in my database so it should show a message saying "Username already exists,".我输入了一个用户名“admin”,但它已经在我的数据库中,所以它应该显示一条消息“用户名已经存在”。 Otherwise: If the username isn't used yet then it will be added in my database.否则:如果用户名尚未使用,那么它将被添加到我的数据库中。 I'm using Visual Studio 2005 and Navicat for MySQL Here is my code:我正在为 MySQL 使用 Visual Studio 2005 和 Navicat 这是我的代码:

conn.Open() 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()

Still a lot of room for improvement, and I typed this out on my phone with no syntax checking, but think it should get you heading in the right direction.还有很大的改进空间,我在手机上输入了这个,没有进行语法检查,但认为它应该让你朝着正确的方向前进。 Things for you to read up on is parametrising your query/insert statements and the Using keyword which can help with managing your db connections.您需要阅读的内容是参数化您的查询/插入语句和 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM