gpt4 book ai didi

mysql - 在数据库中搜索字符串并获取相关信息 VB

转载 作者:行者123 更新时间:2023-11-30 22:46:59 25 4
gpt4 key购买 nike

我希望能够在我的数据库中搜索产品名称或产品 ID 号,然后将有关该产品的任何相关信息加载到文本框中。

我当前的代码没有构建错误,但它似乎没有返回任何信息。它可能只是一些小东西,我是个白痴,但我无法理解这个问题。

 Private Sub btnSearchProducts_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSearchProducts.Click
ds.Clear()

If txtProductName.Text = "" And txtProductID.Text = "" Then
MessageBox.Show("Please enter either a Product ID or Product Name..", "Authentication Error", MessageBoxButtons.OK, MessageBoxIcon.Error)

Else
If txtProductID.Text <> "" Then
For Each ch As Char In txtProductID.Text
If Not Char.IsDigit(ch) Then
txtProductID.Clear()
MsgBox("Please enter a valid Product ID. Only integers are a valid input", MessageBoxButtons.OK, MessageBoxIcon.Error)
Exit Sub
End If
Next
End If

' Connect to DB

Dim conn As New System.Data.OleDb.OleDbConnection()
conn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\Computing Project\Database1.accdb"
Dim Command As New OleDb.OleDbCommand

Try

Dim sql As String = "SELECT * FROM tbl_stock WHERE S_ID = '" & txtProductID.Text & "'OR S_ProductName = '" & txtProductName.Text & "'"
Dim sqlCom As New System.Data.OleDb.OleDbCommand(sql)

'Open Database Connection
sqlCom.Connection = conn
conn.Open()

da = New OleDb.OleDbDataAdapter(sql, conn)
da.Fill(ds, "Stock")

Dim sqlRead As System.Data.OleDb.OleDbDataReader = sqlCom.ExecuteReader()

If sqlRead.Read() Then
txtProductID.Text = CInt(ds.Tables("Stock").Rows(0).Item(0))
txtProductName.Text = ds.Tables("Stock").Rows(0).Item(3)
txtProductPrice.Text = "£" & CDec(ds.Tables("Stock").Rows(0).Item(2))
Else
If txtProductID.Text <> "" Then
MsgBox("Sorry, " & txtProductID.Text & " is not a valid Product ID", MessageBoxButtons.OK, MessageBoxIcon.Error)
txtProductID.Text = ""
End If
If txtProductName.Text <> "" Then
MsgBox("Sorry, " & txtProductName.Text & " is not a valid Product Name", MessageBoxButtons.OK, MessageBoxIcon.Error)
txtProductName.Text = ""
End If
End If
Catch ex As Exception
End Try
End If
End Sub

非常感谢任何帮助

最佳答案

关于此的一些想法,可能会为您指明正确的方向。

  1. 看起来您正在组合两个不同的逻辑过程。填充数据集,然后再次尝试从同一查询中读取。而不是呼吁“阅读”您的 if 语句。在 ds.Tables[0] 上查找可能解决当前问题的行数。
  2. 请查看参数化 SQL 查询,从原始用户条目构建允许恶意操作,如果可以,应尽一切努力避免它。
  3. 查看您的查询,您正在寻找与 ID 或姓名完全匹配的内容。您可以切换到对名称的 LIKE 操作,而不是完全匹配。

关于mysql - 在数据库中搜索字符串并获取相关信息 VB,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29324330/

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