处理MySQL数据库在重复主键上抛出的异常

时间:2015-09-12 12:19:52

标签: mysql vb.net

如何使用错误处理程序,当我在文本框中输入ID并且该ID已经存在于数据库中时,它会说。 “身份证已经存在”

这是我的代码

Public Class frmPawn
    Dim ds As DataSet
    Dim da As MySqlDataAdapter
    Dim cmd As New MySqlCommand

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim con As New MySqlConnection("host=localhost; username=root; password=; database=pawnshop")
        con.Open()
        cmd.Connection = con

        ds = New DataSet
        da = New MySqlDataAdapter("insert into clients (clientid, fname, mname, lname, address, city, prov, zip, contact, birth, sex) values('" & txtId.Text & "','" & txtFname.Text & "','" & txtMname.Text & "','" & txtLname.Text & "','" & txtAddress.Text & "','" & txtCity.Text & "','" & txtProv.Text & "','" & txtZip.Text & "','" & txtContact.Text & "','" & DateTimePicker_DOB.Text & "','" & lblSex.Text & "')", con)
        da.Fill(ds, "clients")
    End Sub


End Class

2 个答案:

答案 0 :(得分:0)

我不会讨论你应该如何真正设计你的系统。但这是你直接要求的

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

     Try
         ' your code here

     Catch mySqlEx As MySqlExeption
         ' Here handle MySql Exceptions
         If mySqlEx.Number = 1068 Then
         . . . . . 
         ' Exception number reference:
         ' http://dev.mysql.com/doc/refman/5.6/en/error-messages-server.html
     Catch ex As Exception
          ' Here handle any other Exceptions
     End Try

End Sub

如您所见,您可以使用MySql for .Net documentation获取所有异常信息,然后在代码中处理。您收到的错误,我相信代码是1068.一旦您运行此代码,您可以放置​​断点并检查您收到的代码然后处理它。

答案 1 :(得分:0)

您可以尝试从数据库中选择具有该ID的行,如果选择了任何内容,则可以运行您的代码。