Question Check if record exists in database, if it doesn't then insert on db

Nikki Sixx

New member
Joined
May 17, 2011
Messages
1
Programming Experience
3-5
The next code is working but when I try to insert an existing record, it gives me an error and I want to add a msgbox to let people now that the username is already taken.
Only the username cannot repeat on the database because it's the primary key.. the rest of the table rows can repeat.

here's the code:

VB.NET:
Dim cn As New OleDbConnection

cn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Fabio\Desktop\Telemoveis\Telemoveis\Db_Tel.accdb"
cn.Open()

Dim da1 As OleDb.OleDbDataAdapter
Dim ds1 As New DataSet
Dim sql As String

sql = "select * from utilizador;"
ds1.Dispose()
da1 = New OleDb.OleDbDataAdapter(sql, cn)

da1.Fill(ds1, "database4")
Dim cb As New OleDb.OleDbCommandBuilder(da1)
Dim novoregisto As DataRow

novoregisto = ds1.Tables("database4").NewRow

novoregisto.Item("Utilizador") = Txt_utilizador1.Text
novoregisto.Item("Passw") = txt_password1.Text
novoregisto.Item("Cargo") = txt_cargo1.Text

ds1.Tables("database4").Rows.Add(novoregisto)

da1.Update(ds1, "database4")

Txt_utilizador1.Clear()
txt_password1.Clear()
Administração.DataGridView2.Update()
Administração.DataGridView2.Refresh()
I hope I can hear from you soon, Thanks.

Greetings, Nikki
 
Last edited by a moderator:
On the first pass to find if it exists I would just do:

VB.NET:
Dim strSQL as string = SELECT COUNT(*) FROM ...WHERE...

VB.NET:
Dim cmd as New OleDBCommand(strSQL, cn)
Dim exists as Boolean = iif(cmd.executescalar() = 0, False, True)
 
Back
Top