【问题标题】:How to pass parameters to dataadapter?如何将参数传递给数据适配器?
【发布时间】:2019-08-30 00:13:45
【问题描述】:

我有下面的代码,我使用 dataadapter 从 sql 数据库表中选择数据,但我抛出了一个错误:

"必须声明标量变量"@UserName"

代码哪里出错了???

我尝试了下面的代码,它会抛出错误“必须声明标量变量”@UserName”

 Dim Query as string ="SELECT *FROM UserLogins WHERE [Login Name]= 
 @Username  AND Password=@passcode"

 // add parameters to dataadapter select command
 SQL.da.SelectCommand.Parameters.AddWithValue("@Username", "%" + 
 txtuserName.Text + "%")
 SQL.da.SelectCommand.Parameters.AddWithValue("@passcode", "%" + 
 txtpasslogin.Text + "%")

  //execute query and fill dataset
        da = New SqlDataAdapter(Query,Con)           
        cb = New SqlCommandBuilder(da)
        ds = New DataSet
        da.Fill(ds)
 Datagridview1.Datasource=ds.tables(0)

【问题讨论】:

  • 您正在向 da.SelectCommand 对象添加参数,然后创建一个新的 da 对象,所以不,不再有任何参数。
  • 感谢您的评论,请您使用代码来澄清您的答案。
  • 尝试在创建新适配器之后添加参数。
  • % 符号是什么意思?这不像它的 =。
  • @Mary 用户名和密码?嗯,够近了,进来吧。

标签: sql vb.net dataadapter sqlparameter sqlcommandbuilder


【解决方案1】:

哇,好吧,这段代码发生了很多奇怪的事情。

首先。两个斜线 (//) 不是 cmets 在 VB.NET 中的完成方式。那是 C# 语法。改用单引号 (')

接下来,您收到的错误是来自 SQL Server 的错误。

"必须声明标量变量@UserName"

LarsTech 在他的评论中特别提到,您提供的代码是先添加变量,然后立即创建 SQLDataAdapter 的新实例。如果您修改代码以先创建数据适配器,然后填充变量,您应该会得到更好的结果。

我不会假设变量 da、cb 和 ds 已经声明,但变量 Con 是在某处声明的。

Dim Query as string ="SELECT * FROM UserLogins WHERE [Login Name]=     
@Username  AND Password=@passcode"

'Note that I moved these two lines up here and made sure they were properly declared
Dim da as New SqlDataAdapter(Query,Con)           
Dim cb as New SqlCommandBuilder(da)

' add parameters to dataadapter select command
da.SelectCommand.Parameters.AddWithValue("@Username", "%" + 
    txtuserName.Text + "%")
da.SelectCommand.Parameters.AddWithValue("@passcode", "%" + 
    txtpasslogin.Text + "%")

' execute query and fill dataset

ds = New DataSet
da.Fill(ds)
Datagridview1.Datasource=ds.tables(0)

最后,你的 sql 语句在 * 和 FROM 之间也应该有一个空格,正如 Mary 在 cmets 中提到的,这里不需要 % 符号,因为你没有做一个 like。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多