VB6 - Update multiple rows where the query matches - vb6

This Query will be used to update multiple rows where it matches... but unable to perform as its not in a loop and ended up adding only the first matched row.
rs.Open "SELECT tbl_club_member.Mid, tbl_club_member.BlockFlat, [tbl_block_flat.Size] FROM tbl_club_member INNER JOIN tbl_block_flat ON tbl_club_member.BlockFlat = tbl_block_flat.BlockFlat WHERE ((Mid(tbl_block_flat.BlockFlat,1,2) Like '" & Me.Text2 & "') And ((tbl_club_member.MemberType) like 'Owner'));", cn, adOpenForwardOnly, adLockReadOnly
MemberID = rs.Fields(0)
Charge = rs.Fields(2) * Me.Text1
With rs
.Fields(0) = NextID 'tid
.Fields(1) = CurDt 'tdate
.Fields(2) = 72 'accid
.Fields(3) = MemberID 'memberid
.Fields(8) = Charge 'amount
.Fields(9) = Combo2.Text 'particular
.Fields(10) = userx
.Fields(11) = Now()
.Update
End With
rs.MoveLast
Exit Sub

You should consider using UPDATE sql.
Update tableA SET tableA.fieldA = 'somevalue' WHERE condition;
Loop and update is not recommended, unless you have complex logic in vb code.
There is an class that maybe helpful.
Option Explicit
'//////////////////////////////////////////////////////////////////////////////
'##summary
'##require
'---Class:CHashTable.cls
'---Import:Microsoft ActiveX Data Objects 2.8 Library
'##reference
'##license
'##author sunsoft
'##create
'##modify
'---20160812:create this class
'//////////////////////////////////////////////////////////////////////////////
'//////////////////////////////////////////////////////////////////////////////
'//
'// Public Declare
'//
'//////////////////////////////////////////////////////////////////////////////
'------------------------------------------------------------------------------
' Interface
'------------------------------------------------------------------------------
'------------------------------------------------------------------------------
' Public Const
'------------------------------------------------------------------------------
'------------------------------------------------------------------------------
' Public DataType
'------------------------------------------------------------------------------
'------------------------------------------------------------------------------
' Public Variable
'------------------------------------------------------------------------------
'------------------------------------------------------------------------------
' Public API
'------------------------------------------------------------------------------
'------------------------------------------------------------------------------
' Event Declare
'------------------------------------------------------------------------------
'//////////////////////////////////////////////////////////////////////////////
'//
'// Private Declare
'//
'//////////////////////////////////////////////////////////////////////////////
'------------------------------------------------------------------------------
' Private Const
'------------------------------------------------------------------------------
'------------------------------------------------------------------------------
' Private DataType
'------------------------------------------------------------------------------
'------------------------------------------------------------------------------
' Private Variable
'------------------------------------------------------------------------------
Private m_Conn As ADODB.Connection
Private m_Command As ADODB.Command
Private m_ConnString As String
Private m_FilePath As String
Private m_AutoConnect As Boolean
'------------------------------------------------------------------------------
' Property Variable
'------------------------------------------------------------------------------
'------------------------------------------------------------------------------
' Private API
'------------------------------------------------------------------------------
'//////////////////////////////////////////////////////////////////////////////
'//
'// Class
'//
'//////////////////////////////////////////////////////////////////////////////
'------------------------------------------------------------------------------
' Initialize
'------------------------------------------------------------------------------
Private Sub Class_Initialize()
m_ConnString = ""
m_FilePath = ""
m_AutoConnect = True
End Sub
'------------------------------------------------------------------------------
' Terminate
'------------------------------------------------------------------------------
Private Sub Class_Terminate()
Set m_Conn = Nothing
Set m_Command = Nothing
End Sub
'//////////////////////////////////////////////////////////////////////////////
'//
'// Events
'//
'//////////////////////////////////////////////////////////////////////////////
'//////////////////////////////////////////////////////////////////////////////
'//
'// Private Property
'//
'//////////////////////////////////////////////////////////////////////////////
'//////////////////////////////////////////////////////////////////////////////
'//
'// Private Methods
'//
'//////////////////////////////////////////////////////////////////////////////
Private Sub OpenConn()
Set m_Conn = New ADODB.Connection
m_Conn.CursorLocation = adUseClient
m_Conn.Open ConnectionString
End Sub
Private Sub CloseConn()
m_Conn.Close
Set m_Conn = Nothing
End Sub
Private Function m_ApostropheCount(ByVal SQL As String) As Long
'count number of "'"
m_ApostropheCount = Len(SQL) - Len(Replace(SQL, "'", ""))
End Function
Private Function m_ProcessNameParams(mSQL As String, mDic As CHashTable, mParams() As Variant) As Boolean
Dim mNewSql As String, mWord As String, mFieldName As String
Dim mParamCount As Long, i As Long, comaCount As Long
Dim mBeginParam As Boolean
If m_ApostropheCount(mSQL) Mod 2 = 1 Then
Err.Raise 110000000, "Symbal "" '"" must be in pairs,please check SQL statement"
End If
'init mDic
mBeginParam = False
mFieldName = ""
mParamCount = 0
For i = 1 To Len(mSQL)
mWord = Mid(mSQL, i, 1)
Select Case mWord
Case " ", ",", ")"
mNewSql = mNewSql & mWord
If mBeginParam Then
ReDim Preserve mParams(mParamCount)
mParams(mParamCount) = mDic.Item(mFieldName)
mFieldName = ""
mParamCount = mParamCount + 1
End If
mBeginParam = False
Case "'"
comaCount = comaCount + 1
mNewSql = mNewSql & mWord
Case "#"
If comaCount Mod 2 = 0 Then
mBeginParam = True
mNewSql = mNewSql & "?"
Else
'odd number of "'" means that "#" is only string of content
mNewSql = mNewSql & mWord
End If
Case Else
If mBeginParam = False Then
mNewSql = mNewSql & mWord
Else
mFieldName = mFieldName & mWord
End If
End Select
Next i
'all done but check last word for that last word maybe param
If mFieldName <> "" Then
ReDim Preserve mParams(mParamCount)
mParams(mParamCount) = mDic.Item(mFieldName)
mFieldName = ""
End If
'return
mSQL = mNewSql
m_ProcessNameParams = True
End Function
Private Function m_GetVarType(ByRef Value As Variant) As ADODB.DataTypeEnum
Select Case VarType(Value)
Case VbVarType.vbString
m_GetVarType = ADODB.DataTypeEnum.adVarWChar
Case VbVarType.vbInteger
m_GetVarType = ADODB.DataTypeEnum.adSmallInt
Case VbVarType.vbBoolean
m_GetVarType = ADODB.DataTypeEnum.adBoolean
Case VbVarType.vbCurrency
m_GetVarType = ADODB.DataTypeEnum.adCurrency
Case VbVarType.vbDate
m_GetVarType = ADODB.DataTypeEnum.adDate
Case 8209
m_GetVarType = ADODB.DataTypeEnum.adLongVarBinary
Case Else
m_GetVarType = ADODB.DataTypeEnum.adVariant
End Select
End Function
'//////////////////////////////////////////////////////////////////////////////
'//
'// Inherit
'//
'//////////////////////////////////////////////////////////////////////////////
'//////////////////////////////////////////////////////////////////////////////
'//
'// Public Property
'//
'//////////////////////////////////////////////////////////////////////////////
Public Property Get ConnectionString() As String
ConnectionString = m_ConnString
End Property
Public Property Let ConnectionString(ByVal vNewValue As String)
m_ConnString = vNewValue
End Property
Public Property Get IsReady() As Boolean
IsReady = IIf(Len(ConnectionString) > 0, True, False)
End Property
'//////////////////////////////////////////////////////////////////////////////
'//
'// Public Methods
'//
'//////////////////////////////////////////////////////////////////////////////
'---------------------Data Base Connection
Public Function DbConnFromFile(ByVal filePath As String) As ADODB.Connection
Dim mConn As New ADODB.Connection
mConn.CursorLocation = adUseClient
mConn.Open "PROVIDER=Microsoft.Jet.OLEDB.4.0;Data Source=" & filePath & ";"
Set DbConnFromFile = mConn
End Function
Public Sub SetConnToFile(ByVal filePath As String)
m_ConnString = "PROVIDER=Microsoft.Jet.OLEDB.4.0;Data Source=" & filePath & ";"
End Sub
Public Sub SetConnToAccdb(ByVal filePath As String)
m_ConnString = "Provider = Microsoft.ACE.OLEDB.12.0;Data Source=" & filePath & ";Persist Security Info=False"
End Sub
Public Sub OpenDB()
m_AutoConnect = False
Call OpenConn
End Sub
Public Sub CloseDB()
m_AutoConnect = True
Call CloseConn
End Sub
'---------------------Querys
Public Function ExecQuery(ByVal SQL As String) As ADODB.Recordset
Dim mRes As New ADODB.Recordset
Set m_Command = New ADODB.Command
If m_AutoConnect Then
Call OpenConn
End If
m_Command.ActiveConnection = m_Conn
m_Command.CommandText = SQL
Set mRes = m_Command.Execute()
'disconnect from database
mRes.ActiveConnection = Nothing
If m_AutoConnect Then
Call CloseConn
End If
Set ExecQuery = mRes
Set m_Command = Nothing
End Function
Public Function ExecParamQuery(ByVal SQL As String, _
ParamArray Params()) As ADODB.Recordset
Dim mRes As ADODB.Recordset
Dim mParamArr As Variant, mParam As Variant
Dim i As Long
Set m_Command = New ADODB.Command
If m_AutoConnect Then
Call OpenConn
End If
m_Command.ActiveConnection = m_Conn
m_Command.CommandText = SQL
m_Command.CommandType = adCmdText
mParamArr = Params
If VarType(Params(0)) = 8204 Then
mParamArr = Params(0)
End If
With m_Command
For Each mParam In mParamArr
Dim Para As ADODB.Parameter
Set Para = .CreateParameter(CStr(i), m_GetVarType(mParam), adParamInput, LenB(mParam))
Para.Value = mParam
If VarType(mParam) = vbEmpty Then
Para.size = 1
ElseIf VarType(mParam) = vbString Then
If LenB(mParam) = 0 Then
Para.size = 1
End If
End If
.Parameters.Append Para
Next
End With
Set mRes = m_Command.Execute()
mRes.ActiveConnection = Nothing
If m_AutoConnect Then
Call CloseConn
End If
Set ExecParamQuery = mRes
Set m_Command = Nothing
End Function
Public Function ExecNamedQuery(ByVal SQL As String, HashedParams As CHashTable) As ADODB.Recordset
Dim mParams() As Variant
m_ProcessNameParams SQL, HashedParams, mParams
Set ExecNamedQuery = ExecParamQuery(SQL, mParams)
End Function
Public Function ExecNonQuery(ByVal SQL As String) As Long
Dim affectedRows As Long
Set m_Command = New ADODB.Command
If m_AutoConnect Then
Call OpenConn
End If
m_Command.ActiveConnection = m_Conn
m_Command.CommandText = SQL
m_Command.CommandType = adCmdText
m_Command.Execute affectedRows
If m_AutoConnect Then
Call CloseConn
End If
Set m_Command = Nothing
ExecNonQuery = affectedRows
End Function
Public Function ExecParamNonQuery(ByVal SQL As String, ParamArray Params()) As Long
Dim i As Long, affectedRows As Long
Dim mParamArr As Variant, mParam As Variant
Set m_Command = New ADODB.Command
If m_AutoConnect Then
Call OpenConn
End If
m_Command.ActiveConnection = m_Conn
m_Command.CommandText = SQL
m_Command.CommandType = adCmdText
mParamArr = Params
If VarType(Params(0)) = 8204 Then
mParamArr = Params(0)
End If
With m_Command
For Each mParam In mParamArr
Dim Para As ADODB.Parameter
Set Para = .CreateParameter(CStr(i), m_GetVarType(mParam), adParamInput, LenB(mParam))
Para.Value = mParam
If VarType(mParam) = vbEmpty Then
Para.size = 1
ElseIf VarType(mParam) = vbString Then
If LenB(mParam) = 0 Then
Para.size = 1
End If
End If
.Parameters.Append Para
Next
End With
m_Command.Execute affectedRows
If m_AutoConnect Then
Call CloseConn
End If
Set m_Command = Nothing
ExecParamNonQuery = affectedRows
End Function
Public Function ExecNamedNonQuery(ByVal SQL As String, HashedParams As CHashTable) As Long
Dim mParams() As Variant
m_ProcessNameParams SQL, HashedParams, mParams
ExecNamedNonQuery = ExecParamNonQuery(SQL, mParams)
End Function
Public Function ExecCreate(ByVal SQL As String) As Variant
Dim mRes As ADODB.Recordset
Set m_Command = New ADODB.Command
If m_AutoConnect Then
Call OpenConn
End If
m_Command.ActiveConnection = m_Conn
m_Command.CommandText = SQL
m_Command.CommandType = adCmdText
m_Command.Execute
m_Command.CommandText = "SELECT ##identity"
Set mRes = m_Command.Execute
If mRes.RecordCount > 0 Then
ExecCreate = mRes.Fields(0).Value
Else
ExecCreate = Empty
End If
If m_AutoConnect Then
Call CloseConn
End If
Set m_Command = Nothing
Set mRes = Nothing
End Function
Public Function ExecParamCreate(ByVal SQL As String, ParamArray Params()) As Variant
Dim mParamArr As Variant, mParam As Variant
Dim mRes As ADODB.Recordset
Dim i As Long
Set m_Command = New ADODB.Command
If m_AutoConnect Then
Call OpenConn
End If
m_Command.ActiveConnection = m_Conn
m_Command.CommandText = SQL
m_Command.CommandType = adCmdText
mParamArr = Params
If VarType(Params(0)) = 8204 Then
mParamArr = Params(0)
End If
With m_Command
For Each mParam In mParamArr
Dim Para As ADODB.Parameter
Set Para = .CreateParameter(CStr(i), m_GetVarType(mParam), adParamInput, LenB(mParam))
Para.Value = mParam
If VarType(mParam) = vbEmpty Then
Para.size = 1
ElseIf VarType(mParam) = vbString Then
If LenB(mParam) = 0 Then
Para.size = 1
End If
End If
.Parameters.Append Para
Next
End With
m_Command.Execute
m_Command.CommandText = "SELECT ##identity"
Set mRes = m_Command.Execute
If mRes.RecordCount > 0 Then
ExecParamCreate = mRes.Fields(0).Value
Else
ExecParamCreate = Empty
End If
If m_AutoConnect Then
Call CloseConn
End If
Set m_Command = Nothing
Set mRes = Nothing
End Function
Public Function ExecNamedCreate(ByVal SQL As String, HashedParams As CHashTable) As Variant
Dim mParams() As Variant
m_ProcessNameParams SQL, HashedParams, mParams
ExecNamedCreate = ExecParamCreate(SQL, mParams)
End Function
Public Function ExecScalar(ByVal SQL As String) As Variant
Dim mRes As ADODB.Recordset
Set mRes = ExecQuery(SQL)
If mRes.RecordCount <= 0 Then
ExecScalar = Empty
Else
ExecScalar = mRes.Fields(0).Value
End If
Set mRes = Nothing
End Function
Public Function ExecParamScalar(ByVal SQL As String, _
ParamArray Params()) As Variant
Dim mRes As ADODB.Recordset
If VarType(Params(0)) = 8204 Then
Params = Params(0)
End If
Set mRes = ExecParamQuery(SQL, Params)
If mRes.RecordCount <= 0 Then
Set ExecParamScalar = Nothing
Else
ExecParamScalar = mRes.Fields(0).Value
End If
Set mRes = Nothing
End Function
Public Function ExecNamedScalar(ByVal SQL As String, HashedParams As CHashTable) As Variant
Dim mParams() As Variant
m_ProcessNameParams SQL, HashedParams, mParams
ExecNamedScalar = ExecParamScalar(SQL, mParams)
End Function
'---------------------Table Structure
Public Function Tables() As ADODB.Recordset
Dim mRes As ADODB.Recordset
If m_AutoConnect Then
Call OpenConn
End If
Set mRes = m_Conn.OpenSchema(adSchemaTables)
mRes.ActiveConnection = Nothing
If m_AutoConnect Then
Call CloseConn
End If
Set Tables = mRes
End Function
Public Function UserTables() As ADODB.Recordset
Dim mRes As ADODB.Recordset
If m_AutoConnect Then
Call OpenConn
End If
Set mRes = m_Conn.OpenSchema(adSchemaTables)
mRes.Filter = "table_type = 'TABLE'"
mRes.ActiveConnection = Nothing
If m_AutoConnect Then
Call CloseConn
End If
Set UserTables = mRes
End Function
Public Function Fields(ByVal TableName As String) As ADODB.Recordset
Dim mRes As ADODB.Recordset
If m_AutoConnect Then
Call OpenConn
End If
Set mRes = m_Conn.OpenSchema(adSchemaColumns)
mRes.Filter = "table_name = '" & TableName & "'"
mRes.Sort = "ORDINAL_POSITION ASC"
mRes.ActiveConnection = Nothing
If m_AutoConnect Then
Call CloseConn
End If
Set Fields = mRes
End Function
Public Function KeyField(ByVal TableName As String) As String
Dim mRes As ADODB.Recordset
Dim mKeyFieldName As String
If m_AutoConnect Then
Call OpenConn
End If
Set mRes = m_Conn.OpenSchema(adSchemaPrimaryKeys)
mRes.Filter = "table_name = '" & TableName & "'"
mRes.ActiveConnection = Nothing
If m_AutoConnect Then
Call CloseConn
End If
If mRes.RecordCount > 0 Then
mRes.MoveFirst
Do While Not mRes.EOF
If mRes.Fields("column_name").Value <> "" Then
mKeyFieldName = mRes.Fields("column_name").Value
Exit Do
End If
Loop
End If
KeyField = mKeyFieldName
End Function
Public Sub ReleaseRecordset(res As ADODB.Recordset)
Set res = Nothing
End Sub

Related

adding data to oracle database in vb6

I have a problem adding data oracle database,it's show me this message(" https://ufile.io/lzpuj ") Run-time ORA-00904:"EMPCODE": invalid identifier.
This is Cody:
Dim connEmp As ADODB.Connection
Dim rsEmp As ADODB.Recordset
Private Sub Command1_Click()
Set rsEmp = New ADODB.Recordset
rsEmp.Open "select * from tablebooks where empcode = '" & Text1.Text & "'",
connEmp, adOpenKeyset, adLockReadOnly, adCmdText
If rsEmp.RecordCount <> 0 Then
MsgBox " ! åÐÇ ÇáßÊÇÈ ãæÌæÏ ÈÇáÝÚá "
rsEmp.Close
Set rsEmp = Nothing
Exit Sub
Else
Set rsEmp = New ADODB.Recordset
rsEmp.Open "select * from tablebooks where empcode = '" & Text1.Text & "'",
connEmp, adOpenKeyset, adLockPessimistic, adCmdText
rsEmp.AddNew
rsEmp!Book_no = Val(Trim(Text1.Text))
rsEmp!Book_name = Trim(Text2.Text)
rsEmp!Author_name = Trim(Text10.Text)
rsEmp!Edition_no = Val(Trim(Text3.Text))
rsEmp!Publisher_place = Trim(Text11.Text)
rsEmp!Part_no = Val(Trim(Text5.Text))
rsEmp!Book_cost = Trim(Text6.Text)
rsEmp!Place_book = Trim(Text7.Text)
rsEmp!Note = Trim(Text9.Text)
rsEmp!Date_publishing = DTPicker1.Value
rsEmp!Subject = Trim(Combo4.Text)
rsEmp!State = Trim(Combo4.Text)
rsEmp.Update
connEmp.Execute "commit"
rsEmp.Close
Set rsEmp = Nothing
Label11.Visible = True
Label11 = " ! ÊãÊ ÇáÅÖÇÝÉ ÈäÌÇÍ "
End If
End Sub
First make sure empcode is exactly the right column name.
Then fix your code. You have two big issues:
It's crazy-vulnerable to Sql Injection attacks.
It tries to re-open the same command on the same connection in the ELSE block for no reason.
The exact fix for #1 depends on which provider you are using (Ole vs Odbc), but this link might help:
Call a parameterized Oracle query from ADODB in Classic ASP
For #2, this is somewhat better:
Dim connEmp As ADODB.Connection
Dim rsEmp As ADODB.Recordset
Private Sub Command1_Click()
Set rsEmp = New ADODB.Recordset
'TODO: Use parameterized query here!
rsEmp.Open "select * from tablebooks where empcode = #empcode '" & Text1.Text & "'",
connEmp, adOpenKeyset, adLockReadOnly, adCmdText
If rsEmp.RecordCount <> 0 Then
MsgBox " ! åÐÇ ÇáßÊÇÈ ãæÌæÏ ÈÇáÝÚá "
rsEmp.Close
Set rsEmp = Nothing
Exit Sub
End If
rsEmp.AddNew
rsEmp!Book_no = Val(Trim(Text1.Text))
rsEmp!Book_name = Trim(Text2.Text)
rsEmp!Author_name = Trim(Text10.Text)
rsEmp!Edition_no = Val(Trim(Text3.Text))
rsEmp!Publisher_place = Trim(Text11.Text)
rsEmp!Part_no = Val(Trim(Text5.Text))
rsEmp!Book_cost = Trim(Text6.Text)
rsEmp!Place_book = Trim(Text7.Text)
rsEmp!Note = Trim(Text9.Text)
rsEmp!Date_publishing = DTPicker1.Value
rsEmp!Subject = Trim(Combo4.Text)
rsEmp!State = Trim(Combo4.Text)
rsEmp.Update
connEmp.Execute "commit"
rsEmp.Close
Set rsEmp = Nothing
Label11.Visible = True
Label11 = " ! ÊãÊ ÇáÅÖÇÝÉ ÈäÌÇÍ "
End Sub

How to use class initialize vb6 to connect to SQL server?

Anyone can help me how can I do for that variable objusername and objpassword of sub login are recognized by the sub Class_Initialize ? I tried this but it does not work.
private cn as ADODB.Connection
private record As ADODB.Recordset
private objusername as variant
private objpassword as variant
Public Sub login(objuser As Variant, objpass As Variant)
Set cn = New ADODB.Connection
cn.ConnectionString = "Provider=SQLOLEDB;Data Source=localhost\SQLExpress;Initial Catalog=bdd;User ID=" & objusername & ";Password=" & objpassword & ""
cn.Open
If cn.State = adStateOpen Then
MsgBox "welcome", vbOKOnly, "connexion"
End If
end sub
Private Sub Class_Initialize()
On Error GoTo erreur
Set cn = New ADODB.Connection
Set record = New ADODB.Recordset
cn.ConnectionString = "Provider=SQLOLEDB;Data Source=localhost\SQLExpress;Initial Catalog=bdd;User ID='" & objusername & "';Password='" & objpassword & "'"
cn.Open
Exit Sub
erreur:
If Err.Number = -2147217843 Then
MsgBox "connection failed"
End If
End Sub
and I call class like this but I have always an error.
Private Sub CmdOK_Click()
dim x as class1
set x = new class1
x.Login text1,text2
End Sub
How can I solve this.
Class_Initialize will execute when you call new class1, as that's before you call Login the code in Class_Initialize has no idea what the username and password are.
Connect in Login instead:
private cn as ADODB.Connection
private record As ADODB.Recordset
private objusername as variant
private objpassword as variant
Public Sub login(objuser As Variant, objpass As Variant)
objusername = objuser
objpassword = objpass
Set cn = New ADODB.Connection
cn.ConnectionString = "Provider=SQLOLEDB;Data Source=localhost\SQLExpress;Initial Catalog=bdd;User ID=" & objusername & ";Password=" & objpassword & ""
cn.Open
...
end sub
Private Sub Class_Initialize()
End Sub
If you want to connect when you create an instance of Class1 use a factory function in a module which is the closest workaround for the lack of constructors.
public function CreateAndLogin(objuser As Variant, objpass As Variant) as class1
set CreateAndLogin= new Class1
CreateAndLogin.login bjuser, objpass
end function
called with
Dim cls as Class1
set cls = CreateAndLogin(text1, text2)

VBScript ADODB.Stream type mismatch

I am writing an HTA application to manage Hyper-V, and I am stuck on the GetVirtualSystemThumbnailImage script. I took the VBScript example from:
https://msdn.microsoft.com/en-us/library/cc160707(v=vs.85).aspx
but that script never actually calls the sub to write the image file. I tried calling the SaveThumbnailImage sub with the arguments being (objOutParams.ImageData), and I get a "Type Mismatch" error on the stream.WriteText line 81. For some reason, the ADODB is rejecting the binary data? I would appreciate any help with this.
option explicit
dim objWMIService
dim managementService
dim fileSystem
const wmiStarted = 4096
const wmiSuccessful = 0
Main()
'-----------------------------------------------------------------
' Main
'-----------------------------------------------------------------
Sub Main()
dim computer, objArgs, strArgs, vmName, vm
set objArgs = WScript.Arguments
if WScript.Arguments.Count = 1 then
computer = Split(objArgs.Unnamed.Item(0),",")(0)
vmName = Split(objArgs.Unnamed.Item(0),",")(1)
else
WScript.Echo "usage: cscript GetVirtualSystemThumbnailImage.vbs hostName,vmName"
WScript.Quit(1)
end if
set fileSystem = Wscript.CreateObject("Scripting.FileSystemObject")
set objWMIService = GetObject("winmgmts:\\" & computer & "\root\virtualization\v2")
set managementService = objWMIService.ExecQuery("select * from Msvm_VirtualSystemManagementService").ItemIndex(0)
set vm = GetComputerSystem(vmName)
if StartVm(vm) then
if GetVirtualSystemThumbnailImage(vm) then
WriteLog "Done"
WScript.Quit(0)
End if
end if
WriteLog "GetVirtualSystemThumbnailImage Failed."
WScript.Quit(1)
End Sub
'-----------------------------------------------------------------
' Retrieve Msvm_VirtualComputerSystem from base on its ElementName
'-----------------------------------------------------------------
Function GetComputerSystem(vmElementName)
' On Error Resume Next
dim query
query = Format1("select * from Msvm_ComputerSystem where ElementName = '{0}'", vmElementName)
set GetComputerSystem = objWMIService.ExecQuery(query).ItemIndex(0)
if (Err.Number <> 0) then
WriteLog Format1("Err.Number: {0}", Err.Number)
WriteLog Format1("Err.Description:{0}",Err.Description)
WScript.Quit(1)
end if
End Function
'-----------------------------------------------------------------
' Save the thumbnail
'-----------------------------------------------------------------
Sub SaveThumbnailImage(thumbnailBytes)
dim stream
Const adTypeText = 2
Const adSaveCreateOverWrite = 2
set stream = CreateObject("ADODB.Stream")
stream.Type = adTypeText
stream.Open
Redim text(ubound(thumbnailBytes) \ 2)
Dim i
for i = lbound(thumbnailBytes) to ubound(thumbnailBytes) step 2
text(i\2) = ChrW(thumbnailBytes(i + 1) * &HFF + thumbnailBytes(i))
next
stream.WriteText text
stream.SaveToFile ".\thumbnail.png", adSaveCreateOverWrite
stream.Close
End Sub
'-----------------------------------------------------------------
' Start the virtual machine
'-----------------------------------------------------------------
Function StartVm(computerSystem)
dim objInParam, objOutParams
StartVm = false
if computerSystem.OperationalStatus(0) = 2 then
StartVm = true
Exit Function
end if
set objInParam = computerSystem.Methods_("RequestStateChange").InParameters.SpawnInstance_()
objInParam.RequestedState = 2
set objOutParams = computerSystem.ExecMethod_("RequestStateChange", objInParam)
if objOutParams.ReturnValue = wmiStarted then
if (WMIJobCompleted(objOutParams)) then
StartVm = true
end if
elseif objOutParams.ReturnValue = wmiSuccessful then
StartVm = true
else
WriteLog Format1("StartVM failed with ReturnValue {0}", wmiStatus)
end if
End Function
'-----------------------------------------------------------------
' Print the thumbnail data
'-----------------------------------------------------------------
Sub PrintThumbnailImage(thumbnailBytes)
dim index
dim i
for index = lbound(thumbnailBytes) to ubound(thumbnailBytes)
WriteLog Format2("{0}:{1} ", index, thumbnailBytes(i))
next
End Sub
'-----------------------------------------------------------------
' Define a virtual system
'-----------------------------------------------------------------
Function GetVirtualSystemThumbnailImage(computerSystem)
dim query, objInParam, objOutParams, virtualSystemsetting
GetVirtualSystemThumbnailImage = false
query = Format1("ASSOCIATORS OF {{0}} WHERE resultClass = Msvm_VirtualSystemsettingData", computerSystem.Path_.Path)
set virtualSystemsetting = objWMIService.ExecQuery(query).ItemIndex(0)
set objInParam = managementService.Methods_("GetVirtualSystemThumbnailImage").InParameters.SpawnInstance_()
objInParam.HeightPixels = 150
objInParam.WidthPixels = 100
objInParam.TargetSystem = virtualSystemsetting.Path_.Path
set objOutParams = managementService.ExecMethod_("GetVirtualSystemThumbnailImage", objInParam)
if objOutParams.ReturnValue = wmiStarted then
if (WMIJobCompleted(objOutParams)) then
GetVirtualSystemThumbnailImage = true
end if
elseif objOutParams.ReturnValue = wmiSuccessful then
Dim strData : strData = objOutParams.ImageData
SaveThumbnailImage(strData)
' PrintThumbnailImage(strData)
GetVirtualSystemThumbnailImage = true
else
WriteLog Format1("GetVirtualSystemThumbnailImage failed with ReturnValue {0}", wmiStatus)
end if
End Function
'-----------------------------------------------------------------
' Handle wmi Job object
'-----------------------------------------------------------------
Function WMIJobCompleted(outParam)
dim WMIJob, jobState
set WMIJob = objWMIService.Get(outParam.Job)
WMIJobCompleted = true
jobState = WMIJob.JobState
while jobState = JobRunning or jobState = JobStarting
WriteLog Format1("In progress... {0}% completed.",WMIJob.PercentComplete)
WScript.Sleep(1000)
set WMIJob = objWMIService.Get(outParam.Job)
jobState = WMIJob.JobState
wend
if (jobState <> JobCompleted) then
WriteLog Format1("ErrorCode:{0}", WMIJob.ErrorCode)
WriteLog Format1("ErrorDescription:{0}", WMIJob.ErrorDescription)
WMIJobCompleted = false
end if
End Function
'-----------------------------------------------------------------
' Create the console log files.
'-----------------------------------------------------------------
Sub WriteLog(line)
dim fileStream
set fileStream = fileSystem.OpenTextFile(".\GetVirtualSystemThumbnailImage.log", 8, true)
' WScript.Echo line
fileStream.WriteLine line
fileStream.Close
End Sub
'------------------------------------------------------------------------------
' The string formatting functions to avoid string concatenation.
'------------------------------------------------------------------------------
Function Format2(myString, arg0, arg1)
Format2 = Format1(myString, arg0)
Format2 = Replace(Format2, "{1}", arg1)
End Function
'------------------------------------------------------------------------------
' The string formatting functions to avoid string concatenation.
'------------------------------------------------------------------------------
Function Format1(myString, arg0)
Format1 = Replace(myString, "{0}", arg0)
End Function

How do I write string to longvarchar in pervasive larger than 32k?

Application written in VB6. DB is Pervasive v9.5.
Currently works:
Public Sub Save()
if rs.State = adStateOpen Then
rs.AddNew
SetFields rs
rs.Update
End If
end sub
Public Sub SetFields(rs as ADODB.Recordset)
rs!Name = strName
StrToField strReport rs!Report
StrToField strResponse rs!Response
end sub
Public Sub StrToField(ByVal str As String, fld As ADODB.Field)
Dim Data As String
Dim StrSize As Long, CharsRead As Long
' for field of LONVARCHAR type only
If fld.Type = adLongVarChar Then
StrSize = Len(str)
Do While StrSize <> CharsRead
If StrSize - CharsRead < BLOCK_SIZE_LONGVARCHAR Then
Data = Mid(str, CharsRead + 1, StrSize - CharsRead)
CharsRead = StrSize
Else
Data = Mid(str, CharsRead + 1, BLOCK_SIZE_LONGVARCHAR)
CharsRead = CharsRead + BLOCK_SIZE_LONGVARCHAR
End If
fld.AppendChunk Data
Loop
Else
' do something
End If
End Sub
Const BLOCK_SIZE_LONGVARCHAR = 4096
This works fine until my report or response variable is larger than 32000 characters. I receive this error message when rs.update is called:
"[Pervasive][ODBC Client Interface] String length exceeds column length Parameter #15. Data truncated."
Can anyone point me in the right direction or let me know if I am missing something. Pervasive Longvarchar max size should be 2GB.
Thanks,
Graham
This code works form me using PSQL v11 (I don't have v9.5).
Dim conn As New ADODB.Connection
Set conn = New ADODB.Connection
conn.ConnectionString = "demodata"
conn.Open
Dim sql As String
Dim cmd As New ADODB.Command
cmd.ActiveConnection = conn
cmd.CommandText = "insert into lvc (f2) values (?)"
Dim parm As New ADODB.Parameter
parm.Name = "f2"
Dim longstring As String
Open "c:\longdata.txt" For Input As #1
Do While Not EOF(1)
Line Input #1, sNextLine
'do something with it
'add line numbers to it, in this case!
sText = sText & sNextLine
Loop
longstring = sText
parm.Value = longstring
cmd.Parameters.Append cmd.CreateParameter("param1", adLongVarChar, adParamInput, Len(longstring), longstring)
cmd.Execute
conn.Close
MsgBox "done"
Basically, you would use parameterized queries rather than the .AddNew method.

"Operation is not allowed when the object is open" error in VB6

When I am trying to execute the program I am getting an error like "operation is not allowed when the object is open".
I am geeting error in second part of the code where .Source = "SELECT * FROM t_data_Comments
Sub DneFroceClose()
Dim lngRecCount As Long
frmDNELoad.lblStatus.Caption = "Updating records in Reclamation and Comments Table..."
frmDNELoad.Refresh
CqDate = Format(Date, "dd/MM/yyyy")
Set rcdreclamation = New ADODB.Recordset
With rcdreclamation
.ActiveConnection = objConn
.Source = "SELECT * FROM T_DATA_reclamation"
.CursorType = adOpenDynamic
.CursorLocation = adUseClient
.LockType = adLockOptimistic
.Open
End With
rcdDNE.MoveFirst
rcdreclamation.MoveFirst
Do Until rcdDNE.EOF
Do Until rcdreclamation.EOF
If rcdDNE.Fields![AccountNbr] = rcdreclamation.Fields![RTProvided] Then
rcdreclamation.Fields![ClaimStatus] = "C"
rcdreclamation.Fields![DateClosed] = CqDate
rcdreclamation.Fields![Audit_LastUpdated] = CqDate
rcdreclamation.Fields![Audit_UserAdded] = "SYSTEM"
rcdreclamation.Update
Call DneComments
Exit Do
Else
rcdreclamation.MoveNext
End If
Loop
rcdDNE.MoveNext
rcdreclamation.MoveFirst
Loop
End Sub
Sub DneComments()
With cmdDNEFRC
.ActiveConnection = objConn
.CommandText = "insert into t_data_Comments (ControlNbr, Audit_DateAdded, Audit_UserAdded, Description, EntryType) values ('" & rcdreclamation("ControlNbr") & "', '" & rcdreclamation("DateClosed") & "', '" & rcdreclamation("Audit_UserAdded") & "', 'Claim force-closed.', 'FORCE-CLS')"
.CommandType = adCmdText
End With
Set rcdDneComments = New ADODB.Recordset
With rcddnefrc
.ActiveConnection = objConn
.Source = "SELECT * FROM t_data_Comments"
.CursorType = adOpenDynamic
.CursorLocation = adUseClient
.LockType = adLockOptimistic
.Open
End With
With rcddnefrc
.Requery
.AddNew
.Fields![ControlNbr] = rcdreclamation.Fields![ControlNbr]
.Fields![Audit_DateAdded] = rcdreclamation.Fields![DateClosed]
.Fields![Audit_UserAdded] = rcdDNE.Fields![Audit_UserAdded]
.Fields![Description] = "Claim force-closed."
.Fields![EntryType] = "FORCE-CLS"
.Update
End With
End Sub
Change the With line to
With rcdDneComments

Resources