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.
Related
I've installed tries recordset in my vba statement.
Unfortunately he accesses only the first line in my database. Who can help me?
I'm not very good in VBA it's my first porject. I hope someone can help me with my code. Thank you
Sub Testbox()
Dim conn, Rs
Dim strSQL As String
Dim auswahl As Integer
auswahl = MsgBox("Die Daten werden geladen", vbOKCancel, "Bitte auswählen")
If auswahl = 1 Then
connstring = "UID=user;PWD=passwort;DRIVER={Microsoft ODBC For Oracle};SERVER=server.WORLD;"
Set conn = New ADODB.Connection
With conn
.ConnectionString = connstring
.CursorLocation = adUseClient
.Mode = adModeRead
.Open
End With
Set Rs = CreateObject("ADODB.Recordset")
strSQL = "select * from table where logdatum =1507"
Rs.Open strSQL, conn, 3, 3
Range("A2:A5000") = Rs("scanclient")
Range("B2:B500") = Rs("Sum")
Range("C2:C500") = Rs("batchclass")
Rs.Close
Set Rs = Nothing
conn.Close
Set conn = Nothing
Else
Exit Sub
End If
End Sub
Unfortunately, it is not possible to print data from Recordset into worksheet like that:
Range("A2:A5000") = Rs("scanclient")
Range("B2:B500") = Rs("Sum")
Range("C2:C500") = Rs("batchclass")
You need to replace this code with the below:
Dim i As Long: i = 1
Do Until Rs.EOF
i = i + 1
Cells(i, 1) = Rs("scanclient")
Cells(i, 2) = Rs("Sum")
Cells(i, 3) = Rs("batchclass")
Call Rs.MoveNext
Loop
'code to load picture into database table
Private Function GetPic()
Dim filelen As Long
Dim numlock As Integer
Dim leftover As Long
Const blocksize = 100000
Dim pic As String
Dim bytedata() As Byte
Dim sfile As Integer
sql = "select PICS from student_record_database " //empty field with no pictures
RES.Open sql, CON, adOpenDynamic, adLockOptimistic
sfile = App.Path & "/mypic/Book1.xls" //error : type mismatch
Open sfile For Binary Access Read As #1
filelen = LOF(sfile)
If filelen = 0 Then
Close sfile
MsgBox ("empty or not found")
Else
numlock = filelen / blocksize
leftover = filelen Mod blocksize
ReDim bytedata(leftover)
Get sfile, , bytedata()
RES(1).AppendChunk bytedata()
ReDim bytedata(blocksize)
For i = 1 To numlock
Get sfile, , bytedata()
RES(1).AppendChunk bytedata()
Next i
RES.Update
Close sfile
End If
End Function
'code to display picture in picture box from table
Private Function ShowPic()
Dim bytedata() As Byte
Dim file As String
Dim filelen As Long
Dim numlock As Integer
Dim leftover As Long
Const blocksize = 100000
file = App.Path & "\image1.jpeg"
Open file For Binary As #1
numlock = filelen / blocksize
leftover = filelen Mod blocksize
bytedata() = RES(1).GetChunk(leftover)
Put file, , bytedata()
For i = 1 To numlock
bytedata() = RES(1).GetChunk(blocksize)
Put file, , bytedata()
Next i
Close file
End Function
Here is my full code to insert pictures using vb in an oracle table database.
Next I display those pictures in picture box of vb application as per their records, but it is showing an error of "type mismatch" and picture is not shown in picture box.
you declared sFile as an integer, but are trying to load a string in it
Dim sFile as string
sfile = App.Path & "/mypic/Book1.xls"
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
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
DBF file is in C:\dbase\clip53\PRG\stkmenu\WPACK3\
DBF file is called WPACKS.CFG (deliberately not .DBF)
The VB6 code in an ActiveX EXE for opening the database and recordset:
Function OpenDatabase(sFile As Variant, Optional sProvider As Variant = "Provider=Microsoft.Jet.OLEDB.4.0") As Variant ' ADODB.Connection
Dim nErr As Long
Dim sErr As String
Dim oConnection As Object 'ADODB.Connection
Set oConnection = CreateObject("ADODB.Connection")
On Error Resume Next
oConnection.open sProvider & ";Data Source=" & sFile
nErr = Err.Number
sErr = Err.Description
On Error GoTo 0
If nErr <> 0 Then
Err.Raise OPENDATABASE_E_NOTFOUND, , sErr
End If
Set OpenDatabase = oConnection
End Function
Function OpenRecordSet(ByRef oDb As Variant, sQuery As Variant, Optional bCmdText As Boolean = False) As Variant ''ADODB.Connection ADODB.Recordset
Const adOpenForwardOnly As Long = 0
Const adOpenStatic As Long = 3
Const adOpenDynamic As Long = 2
Const adOpenKeyset As Long = 1
Const adLockOptimistic As Long = 3
Const adCmdText As Long = 1
Dim oRecordSet As Object 'ADODB.Recordset
Set oRecordSet = CreateObject("ADODB.RecordSet")
If bCmdText Then
oRecordSet.open sQuery, , , adCmdText
Else
oRecordSet.open sQuery, oDb, adOpenKeyset, adLockOptimistic
End If
Set OpenRecordSet = oRecordSet
End Function
The script accessing these methods looks a little like VBScript. It is VBScript, but executed by the aforementioned ActiveX EXE which uses MSScript control and has a whole pile of objects which it can make available to the script engine. A kind of VBScript-on-steroids approach.
uses database
uses system
dim db
dim rs
set db = database.opendatabase("C:\dbase\clip53\PRG\stkmenu\WPACK3\","Provider=Microsoft.Jet.OLEDB.4.0;Extended Properties=dBase III;User ID=Admin;Password=")
set rs = database.openrecordset(db, "SELECT * FROM WPACKS.CFG",true)
system.consolewriteline rs.recordcount
My problem is that I keep getting The connection cannot be used to perform this operation. It is either closed or invalid in this context. when it hits the oRecordSet.open sQuery, , , adCmdText (which I got from a Microsoft site.)
'Tis a tad irritating.
The connection string I use when I need to connect a DBF file is usually something like:
"Driver={Microsoft dBase Driver (*.dbf)};dbq=<filePath>"
It works fine for me.
try using the latest and greatest FoxPro driver.