我目前正在Visual Studio 2019中创建一个基于win form的工具,用于从SQL数据库读取数据。在将正在处理的表单中的字段提取到sqlCommand查询中时,我遇到了困难。
这是我的VB脚本的一部分。请注意,如果没有像filter这样的姓氏,它也可以正常工作,如果我使用硬编码的姓氏,例如'Adams‘,它也可以工作。我也可以直接在SQL中使用变量来实现相同的逻辑。消息弹出窗口按预期显示'Adams‘,但数据网格中不返回任何内容。
下面的屏幕截图显示了运行表单所需的结果,并将其硬编码为'Adams‘。
提前感谢您的帮助:)
Public Class Form4
Public Sub BtnFetchAdastraUser_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnFetchAdastraUser.Click
Dim connetionString As String = "Data Source=xxxxxx;Initial Catalog=xxxxxx;User ID=xxxxx;Password=xxxxx"
Dim dt As New DataTable()
Using connection As New SqlConnection(connetionString)
Dim command As New SqlCommand(
"select
[u].[UserRef],
[u].[UserName],
[u].[FullName]
from dbo.[Users][u]
where
[Obsolete] = 0
and [Surname] like '%" + Surname.Text + "%'", connection
)
command.Connection.Open()
Dim sqlAdaptr As New SqlDataAdapter(command)
Dim ds As New DataTable
sqlAdaptr.Fill(ds)
DataGridView1.DataSource = ds
MsgBox(Surname.Text)
command.Connection.Close()
End Using
End Sub
End Class


发布于 2020-03-17 18:44:22
我想通了。我通过我的MsgBox运行command.CommandText,它突出显示了我在查询中通过的以下问题!
我将文本添加到我所经过的字段的前面。

发布于 2020-03-18 13:59:32
建议您使用参数编写SQL查询语句。可以按如下方式进行更改:
Using connection As New SqlConnection(connetionString)
connection.Open()
Dim command As New SqlCommand(
"select
[u].[UserRef],
[u].[UserName],
[u].[FullName]
from dbo.[Users][u]
where
[Obsolete] = 0
and [Surname] like @Surname", connection
)
command.Parameters.Clear()
command.Parameters.AddWithValue("@Surname", "%" & Surname.Text & "%")
Dim sqlAdaptr As New SqlDataAdapter(command)
Dim ds As New DataTable
sqlAdaptr.Fill(ds)
DataGridView1.DataSource = ds
MsgBox(Surname.Text)
MsgBox(command.CommandText)
command.Connection.Close()
End Usinghttps://stackoverflow.com/questions/60720500
复制相似问题