能否使用Winsock控件传送SQL查询后的数据集给客户机?
请教各位老大,主机收到客户机SQL查询字段后主机查询SQL数据库,
然后怎么使用Winsock连接回发这个数据集呢?
最好能有详细代码,小弟万分感谢!
[解决办法]
给你个可以把记录集跟字节数组相互转换的函数,请引用ADO。
Public Function RsToBin(Rs As Recordset) As Variant
Dim objStream As Stream
Set objStream = New Stream
objStream.Open
objStream.Type = adTypeBinary
Rs.Save objStream, adPersistADTG
objStream.Position = 0
RsToBin = objStream.Read()
Set objStream = Nothing
End Function
Public Function BinToRs( vData As Variant) As Recordset
Dim objStream As Stream
Dim objRs As Recordset
Set objRs = New Recordset
Set objStream = New Stream
objStream.Open
objStream.Type = adTypeBinary
objStream.Write vData
objStream.Position = 0
objRs.Open objStream
Set BinToRs = objRs
Set objRs = Nothing
Set objStream = Nothing
End Function
[解决办法]
举个例子。
客户端发送查询请求:
Private Sub Command1_Click()
Dim strSQL As String
strSQL = "select * from Employees "
If Winsock1.State = sckConnected Then
Winsock1.SendData strSQL
DoEvents
End If
End Sub
' 服务器收到查询请求并执行
Private Sub Winsock1_DataArrival(ByVal bytesTotal As Long)
Dim strBuffer As String
Dim arrData() As Byte
Dim objRec As Recordset
Winsock1.GetData strBuffer, vbString
Set objRec = GetRecordset(strBuffer) ' 执行接受到的查询,其中GetRecordset方法执行SQL语句并返回一记录集
arrData() = RsToBin(objRec) ' 记录集转换成字节数组
Winsock1.SendData arrData ' 送回客户段
DoEvents
End Sub
' 客户端收到响应
Private Sub Winsock1_DataArrival(ByVal bytesTotal As Long)
Dim arrData() As Byte
Dim objRec As Recordset
Winsock1.GetData arrData, vbArray + vbByte
Set objRec = BinToRs(arrData) ' 还原记录集
Set DataGrid1.DataSource = objRec ' 显示数据
End Sub
这些代码只是说明大致的方法,实际上接受数据时还要处理何时接受完成,接受完了以后才能还原成记录集。