创建生成的id号并检入sql数据库(如果已存在)

时间:2017-01-21 02:09:07

标签: sql vb.net

首先,我使用rand()生成唯一的ID号,并将其放在标签中。 我想检查sql数据库中的这个rand()号码,如果它已经存在以避免重复。

并使用此代码

Private Sub generatedid()
    Try
        sqlconn.Open()
        Dim autoID As Integer = Int(Rnd() * 999999) + 1
        Dim logquery As String = "SELECT clientid FROM tbl_clientrecords WHERE ClientID = '" & autoID & "' "
        sqlcomm = New MySqlCommand(logquery, sqlconn)
        sqlread = sqlcomm.ExecuteReader

        Dim resCnt As Integer = 0
        While sqlread.Read
            resCnt += 1

        End While

        If resCnt = 1 Then
            cautoid.Text = Int(Rnd() * (Int(Rnd() * 999999) + 1))
        Else
            cautoid.Text = autoID
        End If
        sqlconn.Close()
    Catch ex As Exception

    End Try
End Sub

但是当我在标签中生成rand()数字并查看sql数据库时。两者都是一样的。导致无法插入新数据。 帮帮我谢谢你。

1 个答案:

答案 0 :(得分:-1)

我确实设法通过循环方法

成功创建没有重复的id 不过,还是谢谢你的帮助

Dim idloop As Boolean = True
    While idloop = True
        Try
            sqlconn.Open()
            Dim autoID As Integer = Int(Rnd() * 999999) + 1
            Dim logquery As String = "SELECT clientid FROM tbl_clientrecords WHERE ClientID = '" & autoID & "' "
            sqlcomm = New MySqlCommand(logquery, sqlconn)
            sqlread = sqlcomm.ExecuteReader

            Dim resCnt As Integer = 0
            While sqlread.Read
                resCnt += 1
            End While

            If resCnt = 1 Then
                MessageBox.Show("oopsss-duplicate")
                idloop = True
            Else
                MessageBox.Show("good")
                cautoid.Text = autoID
                idloop = False
            End If
            sqlconn.Close()
        Catch ex As Exception
            MessageBox.Show("Error")
        End Try

    End While