错误: 填充: 选择命令.连接属性尚未



我正在尝试从数据库中检索二进制数据。

我收到此错误:"错误:填充:选择命令.连接属性尚未"。我找不到错误。

Public Shared Function BinaryData(ByVal sFileName As String) As Byte()
Dim strSql As String
Dim binaryFile As Byte() = Nothing
Dim dt As DataTable
Dim myCommand As New SqlCommand
Dim sqlConn As New SqlConnection
sqlConn = New SqlConnection("Data Source=xxx;Initial Catalog=xx;Persist Security Info=True;User ID=wxx;Password=xx;MultipleActiveResultSets=True;Application Name=EntityFramework")
sqlConn.Open()
myCommand.Connection = sqlConn
strSql = "SELECT Data  FROM tbldrive WHERE Filename = '" + sFileName + "'"
Dim scmd As New SqlCommand(strSql, sqlConn)
dt = DataComponent.DataTableQuery(DataComponent.SqlConn, strSql)
If dt.Rows.Count > 0 Then
Try
binaryFile = DirectCast(dt.Rows(0).Item("Data"), Byte())
Catch ex As Exception
MsgBox(ex.Message)
End Try
End If
Return binaryFile
End Function

看起来您已经在该代码中尝试了一些东西,但不小心将一些尝试的残余物留在那里。

有些事情你可以做一些不同的事情:因为你只关注数据库中的一个项目,你可以使用ExecuteScalar;当代码完成SQL连接和命令时,他们应该有。Dispose(( 调用了它们 - 即使出现问题,Using 语句也会为您处理这个问题。最后,应始终使用 SQL 参数将参数传递给 SQL 查询 - 这样可以使其更安全,并避免担心值中的撇号等内容。

Public Shared Function BinaryData(ByVal sFileName As String) As Byte()
Dim sql As String = "SELECT Data FROM tbldrive WHERE Filename = @fname"
Dim connStr = "Data Source=xxx;Initial Catalog=xx;Persist Security Info=True;User ID=wxx;Password=xx;MultipleActiveResultSets=True;Application Name=EntityFramework"
Dim binaryFile As Byte() = Nothing
Using conn As New SqlConnection(connStr),
cmd As New SqlCommand(sql, conn)
cmd.Parameters.Add(New SqlParameter With {
.ParameterName = "@fname",
.SqlDbType = SqlDbType.NVarChar,
.Size = 255,
.Value = sFileName})
conn.Open()
Dim obj As Object = cmd.ExecuteScalar()
If obj IsNot Nothing Then
Try
binaryFile = DirectCast(obj, Byte())
Catch ex As Exception
MsgBox(ex.Message)
End Try
End If
End Using
Return binaryFile
End Function

(您可能需要调整.SqlDbType.Size参数:它们需要与数据库中的列类型和大小匹配。此外,您可能不需要 MultipleActiveResultSets。

问题似乎是您有两个SqlCommand对象:

Dim myCommand As New SqlCommand
...
myCommand.Connection = sqlConn

它已分配但未使用。

然后,您定义了另一个:

Dim scmd As New SqlCommand(strSql, sqlConn)

那也没有使用。

我不知道你为什么会有这个:

dt = DataComponent.DataTableQuery(DataComponent.SqlConn, strSql)

如果您不使用它,您甚至需要SqlCommand吗? 通过删除未使用的变量来清理代码。

最新更新