我正在尝试从数据库中检索二进制数据。
我得到了这个错误:"Error: Fill: selectcommand.connection property has been“。我找不到错误所在。
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发布于 2020-05-21 03:08:32
看起来您已经在该代码中尝试了一些东西,但意外地将一些尝试的剩余部分留在了其中。
有一些事情您可以做得稍有不同:因为您只需要从数据库中获取一项,所以可以使用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。)
发布于 2020-05-21 03:09:59
问题似乎是您有两个SqlCommand对象:
Dim myCommand As New SqlCommand
...
myCommand.Connection = sqlConn它被分配了,但没有被使用。
那么您已经定义了另一个:
Dim scmd As New SqlCommand(strSql, sqlConn)这也不会被使用。
我不知道你为什么会有这个:
dt = DataComponent.DataTableQuery(DataComponent.SqlConn, strSql)如果你不使用SqlCommand,你还需要它吗?通过删除不使用的变量来清理代码。
https://stackoverflow.com/questions/61920368
复制相似问题