VBScript: I want to take the contents of a file and run an UPDATE statement using the contents of each line - vbscript

I have made a connection to a database. I want to take the contents of a file and run an UPDATE statement using the contents of each line.
Database Connection
Option Explicit
Dim sDir : sDir = "\\Server1\Data"
Dim sCS : sCS = Join(Array( _
"Provider=vfpoledb" _
, "Data Source=" & sDir _
, "Collating Sequence=general" _
), ";")
Dim oCN : Set oCN = CreateObject("ADODB.CONNECTION")
oCN.Open sCS
oCN.Close
File
STAD 1
SECA 2
..
UPDATE Statement
For this line:
STAD 1
It would run:
UPDATE B_SNAME.DBF SET SN_ANALSYS = 1 WHERE SN_ACCOUNT = STAD
I am extremely new to VBScript and DBF. I would have no problem writing a little Bash script to do this on our Linux side but here I am lost.
Please can someone provide some information on how I could do it, or even an example (that would be awesome)? :-)

If you separate the fields with one space or any single character (called a delimiter) you can use the split function to separate the fields. You will end up with something like this (I have not tested this)
Dim strSQL
Dim strFilename
Dim sConnString
Dim scs
Dim oCN
Dim oCmd
Dim fso
Dim f
strFilename = "C:\Temp\MyFile.txt"
sConnString = "Provider=vfpoledb;Data Source=\\Server1\Data;Collating Sequence=general;"
strSQL = "UPDATE B_SNAME.DBF SET SN_ANALSYS = p1 WHERE SN_ACCOUNT = p2"
Set oCN = CreateObject("ADODB.CONNECTION")
oCN.Open sConnString
Dim oCmd
Set oCmd = CreateObject("ADODB.Command")
Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.OpenTextFile(strFilename)
Do Until f.AtEndOfStream
sArray = Split(f.ReadLine, " ")
oCmd.Parameters.Append oCmd.CreateParameter("p1", adChar, adParamInput, 4, sArray(1))
oCmd.Parameters.Append oCmd.CreateParameter("p2", adChar, adParamInput, 8, sArray(0))
oCmd.CommandText = strSQL
oCmd.Execute
Loop
f.Close
If oCN.State = 1 Then oCN.Close
Set oCmd = Nothing
Set oCN = Nothing
Most lines are delimited with either tabs or commas but there is no reason why you cannot use a space as long as it does not appear in your data.

Here is a simple example to read the data file and get each field into a variable. This assumes your data file contains a four character account name followed by five spaces and then a number.
Option Explicit
Const ForReading = 1
Dim fso
Set fso = CreateObject("Scripting.FileSystemObject")
Dim line
Dim sn_analsys
Dim sn_account
Dim dataFile
Set dataFile = fso.OpenTextFile("C:\SomeFolder\data.txt")
Do Until dataFile.AtEndOfStream
line = dataFile.ReadLine
sn_account = Left(line, 4)
sn_analsys = Mid(line, 10)
WScript.Echo "sn_account = " & sn_account
WScript.Echo "sn_analsys = " & sn_analsys
'
' Do whatever processing you need to do...
'
Loop
dataFile.Close
If you change the data file to separate the fields by one space, you can use Split to get each field.
Dim line
Dim fields
Dim dataFile
Set dataFile = fso.OpenTextFile("C:\SomeFolder\data.txt")
Do Until dataFile.AtEndOfStream
line = dataFile.ReadLine
fields = Split(line)
WScript.Echo "sn_account = " & fields(0)
WScript.Echo "sn_analsys = " & fields(1)
WScript.Echo
'
' Do whatever processing you need to do...
'
Loop

Related

Text files handles differently

I am trying to read from a csv.txt file using Ado Recordset
I get no results back when trying..
When I copy the contents of the original file into a new text file, and read from that file, it works just fine.
Any ideas what the reason for this might be?
The second file is smaller in size, about 1/2. That's the only difference I can see. This is driving me mad :-)
'Edit
Update with code & schema.ini
Code:
Sub ImportTextFiles()
Dim objAdoDbConnection As ADODB.Connection
Dim objAdoDbRecordset As ADODB.Recordset
Dim strAdodbConnection As String
Dim pathSource As String
Dim filename As String
pathSource = "C:\Users\me\Desktop\Reports\"
filename = "test1.txt"
'filename = "test2.txt"
strAdodbConnection = "Provider=Microsoft.ACE.OLEDB.12.0;" _
& "Data Source=" & pathSource _
& ";Extended Properties=""text;HDR=yes;FMT=Delimited"";"
Set objAdoDbConnection = CreateObject("Adodb.Connection")
Set objAdoDbRecordset = CreateObject("ADODB.Recordset")
With objAdoDbConnection
.Open (strAdodbConnection)
With objAdoDbRecordset
.Open "Select top 10 * FROM " & filename & " WHERE [Date] > #01/01/2000# ", objAdoDbConnection, adOpenStatic, adLockOptimistic, adCmdText
If Not objAdoDbRecordset.EOF Then objAdoDbRecordset.MoveFirst
Do While Not objAdoDbRecordset.EOF
Debug.Print "Field(0): " & objAdoDbRecordset(0).Value
objAdoDbRecordset.MoveNext
Loop
.Close
End With
.Close
End With
Set objAdoDbRecordset = Nothing
Set objAdoDbConnection = Nothing
End Sub
Schema.ini:
[Test1.txt]
col1=date text
col2=interval integer
col3=application text
[Test2.txt]
col1=date text
col2=interval integer
col3=application text
notepadd++ gave me the answer, file1 is ucs-2 encoded, the newly created utf-8

VBScript for moving like files

I need a script to be able to move files with like names once there are 4 like files.
Example:
Cust-12345.txt
Addr-12345.txt
Ship-12345.txt
Price-12345.txt
The files will always start with those for names, the numbers after the "-" will always be different. I need to be able to search a folder and when all 4 files are there move them into a completed folder.
option explicit
dim objFS : dim strShareDirectory : dim strDumpStorageDir : dim objFolder : dim colFiles : dim re : dim objFile
dim dictResults ' dictionary of [filename] -> [matching substring]
dim dictResultsCount ' dictionary of [matching substring] -> [count]
dim dictResultsFinal ' only the valid entries from dictResults
dim keyItem
dim strMatch
dim message
message = "Yes"
set dictResultsFinal = CreateObject("Scripting.Dictionary")
set dictResults = CreateObject("Scripting.Dictionary")
set dictResultsCount = CreateObject("Scripting.Dictionary")
Set objFS = CreateObject("Scripting.FileSystemObject")
strShareDirectory = "c:\Test"
strDumpStorageDir = "c\Test\Out"
Set objFolder = objFS.GetFolder(strShareDirectory)
Set colFiles = objFolder.Files
Set re = New RegExp
re.Global = True
re.IgnoreCase = False
re.Pattern = "-\d"
Dim curFile, matchValue
Dim i: i = 0
For Each objFile in colFiles
' test if the filename matches the pattern
if re.test(objFile.Name) then
' for now, collect all matches without further checks
strMatch = re.execute(objFile.Name)(0)
dictResults(objFile.Name) = strMatch
' and count
if not dictResultsCount.Exists(strMatch) then
dictResultsCount(strMatch) = 1
else
dictResultsCount(strMatch) = dictResultsCount(strMatch) +1
end if
end if
next
' for testing: output all filenames that match the pattern
msgbox join(dictResults.keys(), vblf)
' now copy only the valid entries into a new dictionary
for each keyItem in dictResults.keys()
if dictResultsCount.Exists( dictResults(keyItem) ) then
if dictResultsCount( dictResults(keyItem) ) = 4 then
dictResultsFinal(keyItem) = 1
end if
end if
next
I had an answer here that involved using an array but, come to think of it, I don't think you even need an array. Just iterate each file and check for the existence of the others.
Set re = New RegExp
re.Global = True
re.IgnoreCase = True
re.Pattern = "\\(Cust|Addr|Ship|Price)-(\d+)\.txt"
For Each File In objFS.GetFolder(strShareDirectory).Files
' Test to make sure the file matches our pattern...
If re.Test(File.Path) Then
' It's a match. Get the number...
strNumber = re.Execute(File.Path)(0).SubMatches(1)
' If all four exist, move them...
If AllFourExist(strNumber) Then
For Each strPrefix In Array("Cust-", "Addr-", "Ship-", "Price-")
objFS.MoveFile strShareDirectory & "\" & strPrefix & strNumber & ".txt", _
strDumpStorageDir & "\" & strPrefix & strNumber & ".txt"
Next
End If
End If
Next
And here's the AllFourExist function (I'm assuming objFS is global):
Function AllFourExist(strNumber)
For Each strPrefix In Array("Cust-", "Addr-", "Ship-", "Price-")
If Not objFS.FileExists(strShareDirectory & "\" & strPrefix & strNumber & ".txt") Then Exit Function
Next
AllFourExist = True
End Function
I'm not sure how the FSO will handle the fact that you're moving files out of a folder that you're currently iterating. If it complains, you may need to resort to an array after all. Something to keep in mind.

VBScript code error when using ActiveX to get data from the database

Here is my code, I am trying to open a connection to our database and then using ActiveX to return all the data from column in a table and then outputting it to a text document. I'm getting this error.
PullData.vbs(41, 1) ADODB.Recordset: Item cannot be found in the
collection corresponding to the requested name or ordinal.
Here is my code, omitting sensitive information:
Const ForReading = 1
Dim sServer
Dim sLogin
Dim sPwd
Dim sDb
Dim oCn
Dim oRs
sServer = ""
sLogin = ""
sPwd = ""
sDb = ""
Set oCn = CreateObject( "ADODB.Connection" ) ' set oCn to create an object called ADODB.Connection
Set oRs = CreateObject( "ADODB.Recordset" ) ' set oRs to create an object called ADODB.Recordset
oCn.ConnectionString = "PROVIDER=SQLOLEDB" & _
";SERVER=" & sServer & _
";UID=" & sLogin & _
";PWD=" & sPwd & _
";DATABASE=" & sDb & " "
oCn.ConnectionTimeout=600
oCn.open 'Open the connection to the server
strSelString = "select CallID from dbo.CallLog" 'this is the SQL statement that runs a query on the DB
oRs.Open strSelString,oCn 'This opens the record set and has two parameters, strSelString and oCn
If oRs.EOF Then 'If open record set is at the end of file then...
wscript.echo "There are no records to retrieve; Check that you have the correct record number." 'echo that there is no records to retrieve.
End if
'if there are records then loop through the fields
Do While Not oRs.EOF ' Do while not open record set is not end of file
strfield = ors("Tracker")
if strfield <> "" then 'If strfield doesn't equal "" then
Set objFileSystem = WScript.CreateObject("Scripting.FileSystemObject") 'Set objFileSystem to create object Scripting.FileSystemObject
Set objOutPutFile = objFileSystem.CreateTextFile("c:\test.txt", True) 'Set objOutPutFile to create object objFileSystem.CreateTextFile
strcomputer = oRs 'strcomputer is set to read the line
wscript.echo strfield
objOutPutFile.WriteLine strfield &"|"
objFileSystem.close
objOutPutFile.close
end if
oRs.MoveNext
oCn.Close
Loop
You ask for the CallID column;
"select CallID from dbo.CallLog"
but then try to read something else:
strfield = ors("Tracker")
so either select Tracker or read CallID.
You could also probably create/open the file outside of the loop.

VBScript/SQL Formatting Issue

Okay so the script that I have written is almost fully functional but I would like to add two things to it. What it currently does is you type in a CallID number that is associated with other data on a database in SQL Server. When you type in the number into the msgbox it retrieves all the other columns that are associated with that particular number and outputs it to the command prompt and also outputs it to a text file on the hard drive. This is good, but the formatting is horrible. How would I go about improving the formatting of the file so it is more reading. Currently it is just a line with space seperating each piece of data. Also what I would like to be able to do is also have the name of each Column under each piece of data that is associated with that column. Any help would be appreciated. Here is my code with sensitive information omitted:
Dim strQuery
strQuery = InputBox("Enter CallID Please:")
Dim sServer
Dim sLogin
Dim sPwd
Dim sDb
Dim oCn
Dim oRs
Dim strFullQuery
Dim strfield
Const ForReading = 1
sServer = ""
sLogin = ""
sPwd = ""
sDb = ""
Set oCn = CreateObject( "ADODB.Connection" ) ' set oCn to create an object called ADODB.Connection
Set oRs = CreateObject( "ADODB.Recordset" ) ' set oRs to create an object called ADODB.Recordset
oCn.ConnectionString = "PROVIDER=SQLOLEDB" & _
";SERVER=" & sServer & _
";UID=" & sLogin & _
";PWD=" & sPwd & _
";DATABASE=" & sDb & " "
oCn.ConnectionTimeout=600
oCn.open 'Open the connection to the server
strFullQuery = "select * from dbo.CallLog where CallID=" + strQuery 'this is the SQL statement that runs a query on the DB
oRs.Open strFullQuery,oCn 'This opens the record set and has two parameters, strFullQuery and oCn
If oRs.EOF Then 'If open record set is at the end of file then...
wscript.echo "There are no records to retrieve; Check that you have the correct record number." 'echo that there is no records to retrieve.
End if
'if there are records then loop through the fields
oRs.MoveFirst 'move to the first object in the record set and set it as the current record
Do Until oRs.EOF ' Do while not open record set is not end of file
Set objFileSystem = WScript.CreateObject("Scripting.FileSystemObject") 'Set objFileSystem to create object Scripting.FileSystemObject
Set objOutPutFile = objFileSystem.CreateTextFile("c:\test.txt", True) 'Set objOutPutFile to create object objFileSystem.CreateTextFile
objOutPutFile.WriteLine strColumnNames
strfield = oRs.GetString
if strfield <> "" then 'If strfield doesn't equal "" then
WScript.echo strfield
objOutPutFile.WriteLine strfield &"|"
'objFileSystem.close
objOutPutFile.close
end If
'oRs.MoveNext 'Move to the next object in the record set
Loop
oCn.Close
You can add space to make fixed-widths. Let's say you know that every field will be 20 characters or less:
objOutPutFile.WriteLine strfield & String(20-Len(strfield)," ") & "|"

How to read an Excel file(97-03) in Visual Basic 6.0

Can anybody tell me how to read an Excel file in visual basic 6.0 and import all the values into a listview or datagridview,want to use a simple and efficient technique to achieve this. can anyone help me to solve this
This should import data from an Excel file into a ListView:
Dim ExcelObj As Object
Dim ExcelBook As Object
Dim ExcelSheet As Object
Dim i As Integer
Set ExcelObj = CreateObject("Excel.Application")
Set ExcelSheet = CreateObject("Excel.Sheet")
ExcelObj.WorkBooks.Open App.Path & "\ExcelFile.xls"
Set ExcelBook = ExcelObj.WorkBooks(1)
Set ExcelSheet = ExcelBook.WorkSheets(1)
Dim l As ListItem
lvwList.ListItems.Clear
With ExcelSheet
i = 1
Do Until .cells(i, 1) & "" = ""
Set l = lvwList.ListItems.Add(, , .cells(i, 1))
l.SubItems(1) = .cells(i, 2)
l.SubItems(2) = .cells(i, 3)
l.SubItems(3) = .cells(i, 4)
i = i + 1
Loop
End With
ExcelObj.WorkBooks.Close
Set ExcelSheet = Nothing
Set ExcelBook = Nothing
Set ExcelObj = Nothing
I'd be a lot more likely to use a grid control of some sort rather than a ListView for this, but...
Since you're merely bringing in values without metadata (formatting) you can use one of Jet's Excel IISAMs to do this and it even works on machines where Excel is not installed!
Dim SheetName As String
Dim RS As ADODB.Recordset
Dim LI As ListItem
Dim I As Integer
'Look up 1st Worksheet (or just hardcode its Name).
'
'Notes:
' o Can use Excel 8.0 or Excel 5.0 to read most Excel 7.0/97
' Workbooks, but there is no IISAM specifically for Excel 7.0.
' o Use HDR=Yes if your Worksheet has a header row.
With CreateObject("ADOX.Catalog")
.ActiveConnection = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source='" _
& App.Path & "\sample.xls';" _
& "Extended Properties='Excel 5.0;HDR=No'"
SheetName = .Tables(0).Name
Set RS = New ADODB.Recordset
Set RS.ActiveConnection = .ActiveConnection
End With
'The "Table" name can be a range too, e.g. [Sheet1$A1C7]
With RS
.Open "[" & SheetName & "]", _
, _
adOpenForwardOnly, _
adLockReadOnly, _
adCmdTable
ListView.ListItems.Clear
ListView.View = lvwReport
For I = 0 To .Fields.Count - 1
ListView.ColumnHeaders.Add , , .Fields(I).Name
Next
Do Until .EOF
Set LI = ListView.ListItems.Add(, , CStr(.Fields(0).Value))
For I = 1 To .Fields.Count - 1
LI.SubItems(I) = CStr(.Fields(I).Value)
Next
.MoveNext
Loop
.Close
End With

Resources