Try
con.Open()
comm.Connection = con
comm.CommandText = "insert into [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 Successfully Saved")
con.Close()
Catch
Finally
End Try
答案 0 :(得分:1)
除非您更改表格以使其中一个列存在unqiue约束,否则在插入重复数据时将无法获得异常。但是,您可以始终使用SQL来确保不会添加重复条目,而不是尝试生成错误。假设您正在尝试保留唯一的用户名,您可以像这样编写SQL:
comm.CommandText = @"IF NOT EXISTS(SELECT * FROM [adminanduser] WHERE [username] = @username)
INSERT INTO [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);
如果您希望继续产生错误,请尝试
ALTER TABLE [adminanduser]
ADD UNIQUE (username)
下次尝试插入重复的用户名时,应该抛出异常