mysqlvb.netnavicat

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()

Solution

  • 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