Click here to Skip to main content
15,881,281 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
I have to add items to database, but need to make sure that one item is unique. what do i do here?

e.g lest say i need to add 100 rows of three columns each (school name idcard_num)

it is obvious that name should be unique here, while the rest can have duplicates

1 should i create a unique field , and spit out the database errors that will be thrown to the user?
2. should i check each items before adding?

i have this

VB
Dim conn As New SQLiteConnection("Data Source=" & DBPath)
        'conn.SetPassword(dbPassword)
        conn.Open()
        Dim cmd As New SQLiteCommand(conn)
        Dim mytransaction As SQLiteTransaction = conn.BeginTransaction()
        Try


            '// insert courses //
            For i = 0 To UBound(oCourses)
                cmd = New SQLiteCommand("INSERT INTO courses ([code]," & _
                    "[title],[unit]) VALUES (@code,@title,@unit)", conn)
                cmd.Parameters.AddWithValue("@code", oCourses(i).Code)
                cmd.Parameters.AddWithValue("@title", oCourses(i).Title)
                cmd.Parameters.AddWithValue("@unit", oCourses(i).Unit)

                'Debug.Print(cmd.CommandText)
                cmd.ExecuteNonQuery()
              Next
            mytransaction.Commit()
            Return Nothing
        Catch ex As Exception
            mytransaction.Rollback()
            Debug.Print(ex.Message)
            Return ex.Message
        Finally
            cmd.Dispose()
            conn.Dispose()
            mytransaction.Dispose()
        End Try
Posted

i will suggest you to go with approach 1 but do not throw the exception as it is.Check it before like if it's related to unique key display a proper message saying "Name already exists in the database."
 
Share this answer
 
Comments
Cool Smith 16-Jun-11 4:26am    
i need to add alot of rows, so what do i do it row10 has the duplicate value, move to next row or abort the whole operation
CS2011 16-Jun-11 4:47am    
Well this depends on your requirement. But if i am at your place i would stop the insert operation as data given is wrong and ask the user to correct the data first. But again you can keep the bad data in another file and continue with the insert and inform the user once the operation is complete.
Checking all the items before adding will be an overhead. I suggest you go with #1. Just make sure to handle exceptions properly so users will not freak out when they see technical errors. :)
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900