gpt4 book ai didi

vb.net - 在 vb.net 中添加记录并使用 elseif 检查记录是否存在

转载 作者:行者123 更新时间:2023-12-02 15:28:20 25 4
gpt4 key购买 nike

我是 vb.net 新手..提前抱歉。 谁能帮我看看我的 elseif 代码行有什么问题吗?

    Dim con As SqlConnection = New SqlConnection("Data Source=PC11-PC\kim;Initial Catalog=ordering;User ID=sa;Password=123")
Dim cmd1 As SqlCommand = New SqlCommand("Select * from Customer", con)

Dim first1 As String
Dim second2 As String
first1 = "FirstName"
second2 = "LastName"

con.Open()
If TextBox1.Text = "" Or TextBox2.Text = "" Then
MsgBox("Please fill-up all fields!", MsgBoxStyle.Exclamation, "Add New Customer!")
'this will supposedly display error message for "User Already Exist"
' ElseIf textbox1.text = first1 and textbox2.text = second2 Then
' MsgBox("User Already Exist!", MsgBoxStyle.Exclamation, "Add New User!")
Else
Dim cmd As SqlCommand = New SqlCommand("Insert into [ordering].[dbo].[Customer] ([FirstName],[LastName]) values ('" + TextBox1.Text + "','" + TextBox2.Text + "')", con)
cmd.ExecuteNonQuery()
MsgBox("Records Successfully Added!", MsgBoxStyle.Information, "Add New Customer!")
TextBox1.Text = ""
TextBox2.Text = ""
con.Close()

End If

最佳答案

您需要通过执行SELECT * FROM Customer查询来实际检查用户是否已经存在,但您需要添加WHERE子句,如下所示:

If TextBox1.Text = "" Or TextBox2.Text = "" Then
MsgBox("Please fill-up all fields!", MsgBoxStyle.Exclamation, "Add New Customer!")
Else
Dim theQuery As String = "SELECT * FROM Customer WHERE FirstName=@FirstName AND LastName=@LastName"
Dim cmd1 As SqlCommand = New SqlCommand(theQuery, con)
cmd1.Parameters.AddWithValue("@FirstName", TextBox1.Text)
cmd1.Parameters.AddWithValue("@LastName", TextBox2.Text)

Using reader As SqlDataReader = cmd1.ExecuteReader()
If reader.HasRows Then
' User already exists
MsgBox("User Already Exist!", MsgBoxStyle.Exclamation, "Add New User!")
Else
' User does not exist, add them
Dim cmd As SqlCommand = New SqlCommand("Insert into [ordering].[dbo].[Customer] ([FirstName],[LastName]) values ('" + TextBox1.Text + "','" + TextBox2.Text + "')", con)
cmd.ExecuteNonQuery()
MsgBox("Records Successfully Added!", MsgBoxStyle.Information, "Add New Customer!")
TextBox1.Text = ""
TextBox2.Text = ""
End If
End Using

con.Close()
End If
<小时/>

Note: I added the usage of a parameterized query in the SELECT * query. You should prefer parameterized queries to in-line SQL because it will protect your code from SQL Injection attacks. Never trust the data typed in by the user.

关于vb.net - 在 vb.net 中添加记录并使用 elseif 检查记录是否存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20649548/

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