asp.net - how can i try and catch duplicate data in the database -
try con.open() comm.connection = con comm.commandtext = "insert [adminanduser] (username,firstname,lastname,email,password,usertype) values ('" & textbox1.text & "','" & textbox2.text & "','" & textbox3.text & "','" & textbox4.text & "','" & textbox5.text & "','" & label6.text & "')" comm.executenonquery() response.write("data saved") con.close() catch end try
unless alter table such there unqiue constraint on 1 of columns, not able exception when inserting duplicate data. rather attempting generate error though, use sql ensure duplicate entry won't added. presuming trying keep unique usernames, write sql this:
comm.commandtext = @"if not exists(select * [adminanduser] [username] = @username) insert [adminanduser] select @username,@firstname,@lastname,@email,@password,@usertype"; comm.parameters.addwithvalue("@username", textbox1.text); comm.parameters.addwithvalue("@firstname", textbox2.text); comm.parameters.addwithvalue("@lastname", textbox3.text); comm.parameters.addwithvalue("@email", textbox4.text); comm.parameters.addwithvalue("@password", textbox5.text); comm.parameters.addwithvalue("@usertype", textbox6.text);
if rather go down road of generating error, try
alter table [adminanduser] add unique (username)
that should throw exception next time attempt insert duplicate username
Comments
Post a Comment