gpt4 book ai didi

mysql - NullReferenceException 未处理?

转载 作者:行者123 更新时间:2023-11-30 00:34:40 24 4
gpt4 key购买 nike

当我触发 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

最佳答案

我会使用 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 注入(inject)......使用参数化 SQL 或其他方法来限制风险。

关于mysql - NullReferenceException 未处理?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22272701/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com