I need to use a Try/Catch block to check for duplicate productkey entry, however I am unsure of the exact syntax to do so.
Anyone care to get me moving in the right direction?
Printable View
I need to use a Try/Catch block to check for duplicate productkey entry, however I am unsure of the exact syntax to do so.
Anyone care to get me moving in the right direction?
Try
{
}
Catch
{
}
Finally
{
}
i usually do something like this:
Code:'For VB
Try
'some code that could error
Catch (ex As Exception)
'This is where ex would be your exception, you can get
'the error message with ex.Message
Finally
'This will execute no matter what, error or not
//In C#
try
{
\\some code that could error
}
catch (Exception ex)
{
\\This is where ex would be your exception, you can get
\\the error message with ex.Message
}
finally
{
\\This will execute no matter what, error or not
}
If you're checking for duplicate entries in a database, you shouldn't be relying on a catch{} block to do this for you. That would be inefficient and illogical. Let your stored procedure determine this.Quote:
Originally Posted by Blakk_Majik
mendhak, I couldn't agree more.
However, the instructor has specified this for the assignment, which is the only reason I'm doing it.
Anyway, I should have been more clear.
I know how to set up the try/catch/finally structure, I just need the syntax to validate the entry.
Mendhak, do you have an example of a procedure that would validate the entry instead of using the try/catch?
I hate it when this happens.Quote:
Originally Posted by Blakk_Majik
I of course will not give you code, since you have an instructor which implies that you are learning. Therefore you should learn to do this yourself, we will only give you pointers. (Metaphorical pointers, not programmatic ones)
Now, it isn't clear from your posts whether you want to:
a) Insert a row into your table and find out if a duplicate ID is already there (which will raise an exception)
b) Just find out if there happen to be two rows in your table with duplicate IDs
c) For a given ID, find out if a row already exists in the table
Should I also assume that you require a try...catch for any of the above cases, as your instructor has specified?
Which of the above cases are you going for?
I must try to insert a row, then check for the duplicate entry.
His instructions are often vague, and his teaching leaves MUCH to be desired. He knows his stuff, but he is horrible at getting the message across to the students.
We have not really covered try/catch in this course, or my vb.net programming course, which is why I'm having the trouble.
In your try block, do the insert. Use the ExecuteNonQuery method. If a row with the same ID exists, an exception will be thrown. Not just any exception, it will be (probably) a SqlException. Handle this, and look at ex.Message.
Once you receive this type of exception with that message, you know that a row already exists. Display such a message to the user then.