user3882642
user3882642

Reputation: 31

How to know if the given data already exists in the Database?

I am using VB 2008 as my language and MySQL as the database server.

What I'm trying to do is a registration form where it will let the user know if the ID they inputted is already taken. i already can add the data in the database, the only problem is that i can't seem to reject the data inputted if the ID already exists on my database.

I already tried to Google it, but all they give is PhP codes, Can someone give me the specific code for this condition?

This is what i have tried so far:

    Dim DV As String = "Select PATIENTNO From PATIENTINFO Where ='" & text_PNo.Text & "'"

    Try
        MysqlConn.Open()
        With SqlCommand
            .CommandText = sqlquery
            .Connection = MysqlConn
            If DV = text_PNo.Text Then
               MsgBox("ID already exists")
            Else
             'This is where inserting data in database will take place,
            End If

        End With
        SqlCommand.ExecuteNonQuery()

    Catch myerror As MySqlException
        MessageBox.Show("Cannot connect to database: " & myerror.Message)

    Finally
        MysqlConn.Dispose()
    End Try

Upvotes: 0

Views: 258

Answers (1)

O. Jones
O. Jones

Reputation: 108641

With respect, you're not very close.

For one thing, your query expands to

Select PATIENTNO From PATIENTINFO Where ='12345'

That is not a valid MySQL query. You need something like this instead.

Select PATIENTNO From PATIENTINFO Where PATIENTNO ='12345'

Secondly, you have to actually run the query after you connect to the database. Here's an example from the MySQL documentation http://dev.mysql.com/doc/refman/5.0/es/connector-net-examples-mysqldatareader.html

Finally, you might try using an INSERT query to insert the id number into the table. If the INSERT fails on a duplicate key violation, you know that ID was already present.

Upvotes: 1

Related Questions