简体   繁体   中英

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,". 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:

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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