当我触发IF
语句时发生错误或者如果我将文本框留空,应用程序不应该关闭并修复文本框问题,但事实并非如此。
并指向Dim i As Integer = cmd.ExecuteNonQuery()
Imports MySql.Data.MySqlClient
Public Class Form3
Public sConnection As New MySqlConnection
Private Sub Form3_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
If sConnection.State = ConnectionState.Closed Then
sConnection.ConnectionString = "server=localhost;user id=root;database=db"
sConnection.Open()
End If
LoadPeople()
End Sub
Private Sub btnsave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnsave.Click
Dim Query As String
If txtfname.Text = "" Or txtlname.Text = "" Or txtmname.Text = "" Or txtparty.Text = "" Or txtyr.Text = "" Or cmbpos.Text = "" Then
MessageBox.Show("Please complete the required fields..", "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
Else
Query = "INSERT INTO candidate(cfname,cmname,clname,cpos,cyr,cparty) VALUES('" & txtfname.Text & "','" & txtmname.Text & "','" & txtlname.Text & "','" & cmbpos.Text & "','" & txtyr.Text & "','" & txtparty.Text & "')"
End If
Dim cmd As MySqlCommand = New MySqlCommand(Query, sConnection)
Dim i As Integer = cmd.ExecuteNonQuery()
If (i > 0) Then
MsgBox("Record Inserted")
Else
MsgBox("Record is not Inserted")
End If
sConnection.Close()
txtfname.Text = ""
txtlname.Text = ""
txtmname.Text = ""
txtparty.Text = ""
txtyr.Text = ""
cmbpos.Invalidate()
txtfname.Focus()
LoadPeople()
End Sub
答案 0 :(得分:0)
我会使用try catch ....
Try
cmd.ExecuteNonQuery()
MsgBox("Record Inserted")
Catch ex as Exception
MsgBox("Error:" & ex.message)
Finally
'Optional but I would use it to close of DB Connections
End Try
您也容易受到SQL注入攻击....使用参数化SQL或其他方法来限制风险。