Text files handles differently - text-files

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

Related

visual basic 6 load html file into text1: not loading all of the content

here is my code , am trying to load html file from app.path how ever it is not populating all the data only half of it, am not sure why.
i expected the data to be populated till the end of the file.
Public Function ReadTextFileIntoString(strPathToFile As String) As String
Dim objFSO As New FileSystemObject
Dim objTxtStream As TextStream
Dim strOutput As String
Set objTxtStream = objFSO.OpenTextFile(strPathToFile)
Do Until objTxtStream.AtEndOfStream
strOutput = strOutput + objTxtStream.ReadLine
Loop
objTxtStream.Close
Text1.text = Text1.text & strOutput
End Function
Private Sub Command8_Click()
'Open App.Path & "\" & "File.html" For Input As #1
ReadTextFileIntoString App.Path & "\" & "File.html"
End Sub

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

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

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 update a recordset

here is my code
Dim Cn1 As ADODB.Connection
Dim iSQLStr As String
Dim field_num As Integer
Set Cn1 = New ADODB.Connection
Cn1.ConnectionString = _
"Driver={Microsoft Text Driver (*.txt; *.csv)};" & _
"DefaultDir=" & "C:\path\"
Cn1.Open
iSQLStr = "Select * FROM " & "file.txt" ' & " ORDER BY " & txtField.Text
field_num = CInt(1) - 1
Set Rs1 = Cn1.Execute(iSQLStr)
lstResults.Clear
While Not Rs1.EOF
DoEvents
Rs1.Fields(field_num).Value = "qaz"
If IsNull(Rs1.Fields(field_num).Value) Then
lstResults.AddItem "<null>"
Else
lstResults.AddItem Rs1.Fields(field_num).Value
End If
Rs1.MoveNext
Wend
The error i get is in this line
Rs1.Fields(field_num).Value = "qaz"
it says "The current recordset does not support updating", what is wrong in the code?
I'm not sure if this is valid for text files but with SQL Server you need to change the LockTypeEnum Value setting to allow editing see this link, the default is adLockReadOnly
Edit
According to this link it is not possible to edit a text file via ADO.

How can I upload a file to an Oracle BLOB field using VB6?

I want to take a file from disk and upload it into an Oracle BLOB field, using VB6. How can I do that?
Answering my own question, for reference:
Public Function SaveFileAsBlob(fullFileName As String, documentDescription As String) As Boolean
'Upload a binary file into the database as a BLOB
'Based on this example: http://www.codeguru.com/forum/printthread.php?t=337027
Dim rstUpload As ADODB.Recordset
Dim pkValue AS Long
On Error GoTo ErrorHandler
Screen.MousePointer = vbHourglass
'Create a new record (but leave document blank- we will update the doc in a moment)
'the where clause ensures *no* result set; we only want the structure
strSQL = "SELECT DOC_NUMBER, DOC_DESC, BLOB_FIELD " & _
" FROM MY_TABLE " & _
" WHERE PRIMARY_KEY = 0"
pkValue = GetNextPKValue
Set rstUpload = New ADODB.Recordset
With rstUpload
.CursorType = adOpenKeyset
.LockType = adLockOptimistic
.Open strSQL, myConn
.AddNew Array("DOC_NUMBER", "DOC_DESC"), _
Array(pkValue, documentDescription)
.Close
End With
'They may have the document open in an external application. Create a copy and work with that copy
Dim tmpFileName As String
tmpFileName = GetTempPath & ExtractFileName(fullFileName)
'if the tmp file exists, delete it
If Len(Dir(tmpFileName)) > 0 Then
Kill tmpFileName
End If
'see this URL for info about this subroutine:
'http://stackoverflow.com/questions/848087/how-can-i-copy-an-open-file-using-vb6
CopyFileEvenIfOpen fullFileName, tmpFileName
'Now that our record is inserted, update it with the file from disk
Set rstUpload = Nothing
Set rstUpload = New ADODB.Recordset
Dim st As ADODB.Stream
rstUpload.Open "SELECT BLOB_FIELD FROM MY_TABLE WHERE PRIMARY_KEY = " & pkValue
, myConn, adOpenDynamic, adLockOptimistic
Set st = New ADODB.Stream
st.Type = adTypeBinary
st.Open
st.LoadFromFile (tmpFileName)
rstUpload.Fields("BLOB_FIELD").Value = st.Read
rstUpload.Update
'Now delete the temp file we created
Kill (tmpFileName)
DocAdd = True
ExitPoint:
On Error Resume Next
rstUpload.Close
st.Close
Set rstUpload = Nothing
Set st = Nothing
Screen.MousePointer = vbDefault
Exit Function
ErrorHandler:
DocAdd = False
Screen.MousePointer = vbDefault
MsgBox "Source: " & Err.Source & vbCrLf & "Number: " & Err.Number & vbCrLf & Err.Description, vbCritical, _
"DocAdd Error"
Resume ExitPoint
End Function

Resources