I did code for procedure that prompts for a .jpeg file, converts that file to a Byte array, and saves the Byte Array to the table using the Append chunk method.
Another procedure retrieves the picture image from the table using the GetChunk method, converts the data to a file and displays that file in the Picture box.
Now, my question is that how do I save that image displayed in picture box into the database, so that I can perform operations like: add/update etc.
I did something like this way:
Private Sub CmdSave_Click()
if(cmbRNO=" ") then
sql = "INSERT INTO STUDENT_RECORD_DATABASE(ROLLNO,PICS)"
sql = sql + "VALUES(" & RNo & ","& picture1.picture &")"
Set RES = CON.Execute(sql)
Else
sql = "UPDATE STUDENT_RECORD_DATABASE SET "
sql = sql + "ROLLNO= " & Val(CmbRNO) & ","
sql = sql + "PICS=" & Picture1.Picture & " "
sql = sql + "WHERE ROLLNO= " & Val(CmbRNO) & ""
Set RES = CON.Execute(sql)
End If
End Sub
<code for appendchunk method>
Public Sub Command1_Click()
Dim PictBmp As String
Dim ByteData() As Byte 'Byte array for Blob data.
Dim SourceFile As Integer
' Open the BlobTable table.
strSQL = "Select ID, DOC from LOB_TABLE WHERE ID = 1"
Set Rs = New ADODB.Recordset
Rs.CursorType = adOpenKeyset
Rs.LockType = adLockOptimistic
Rs.Open strSQL, Cn
' Retrieve the picture and update the record.
CommonDialog1.Filter = "(*.jpeg)|*.jpeg"
CommonDialog1.ShowOpen
PictBmp = CommonDialog1.FileName
' Save Picture image to the table column.
SourceFile = FreeFile
Open PictBmp For Binary Access Read As SourceFile
FileLength = LOF(SourceFile) ' Get the length of the file.
If FileLength = 0 Then
Close SourceFile
MsgBox PictBmp & " empty or not found."
Exit Sub
Else
Numblocks = FileLength / BlockSize
LeftOver = FileLength Mod BlockSize
ReDim ByteData(LeftOver)
Get SourceFile, , ByteData()
Rs(1).AppendChunk ByteData()
ReDim ByteData(BlockSize)
For i = 1 To Numblocks
Get SourceFile, , ByteData()
Rs(1).AppendChunk ByteData()
Next i
Rs.Update 'Commit the new data.
Close SourceFile
End If
End Sub
While trying to save image to specific record, run-time error occurs:
inconsistent datatype,expected BLOB got number
Where as:
?sql
UPDATE STUDENT_RECORD_DATABASE SET ROLLNO= 132,PICS=688195876 WHERE ROLLNO= 132
Related
I am trying to do a small program on VB 6.0 to find the records in database and print it in text box based on combo box selection but i failed to find a code which allow me to do this.
Any help please.
Dim adoCon
Dim adoRs
Dim strSQL As String
Dim strDB As String
'Change YourDatabaseName to actual database you have
strDB = "c:\path\YourDatabaseName.accdb"
Set adoCon = CreateObject("ADODB.Connection")
adoCon.Open "Provider = Microsoft.ACE.OLEDB.12.0; " & _
"Data Source = " & strDB & ";" & _
"Persist Security Info = False;"
'Change Table1 to your table name in MS Access
'change the name of combobox and the fieldname in MS Access table
'
'''''''''''''''''''''''''''''''''''''''''''''''''' ''''''''''''''''''''''
' if combo is numeric
strSQL = "SELECT [fieldNameToReturn] FROM Table1 Where [fieldName] = " + [combo].Value + ";"
' if combo is text
'strSQL = "SELECT [fieldNameToReturn] FROM Table1 Where [fieldName] = '" + [combo].Value + "';"
'''''''''''''''''''''''''''''''''''''''''''''''''' '''''''''''''''''''''''
Set adoRs = CreateObject("ADODB.Recordset")
'Set the cursor type we are using so we can navigate through the recordset
adoRs.CursorType = 2
'Set the lock type so that the record is locked by ADO when it is updated
adoRs.LockType = 3
'Open the tblComments table using the SQL query held in the strSQL varaiable
'adoRs.Open strSQL, adoCon
If Not adoRS.Eof() Then
[yourTextBox] = adoRs(0)
End If
adoRs.Close
adoCon.Close
Set adoRs = Nothing
Set adoCon = Nothing
"BOF" below is not a typo. If the recordset is empty (the query returned no records) BOF will be true.
adoRs.Open strSQL, adoCon
If Not adoRS.BOF Then
'If not _BOF_ we have records so load the first record
adoRs.MoveFirst
'If first field is a string then use this
[yourTextBox] = adoRs.Fields(0).Value
'If first field is numeric then use this
[yourTextBox] = CStr(adoRs.Fields(0).Value)
Else
Msgbox "No records returned."
End If
If you were processing multiple records you would still do the MoveFirst and then loop until EOF was true, processing each record. The MoveNext will set EOF = True when there are no more records to process.
adoRs.Open strSQL, adoCon
If Not adoRS.BOF Then
'If not _BOF_ we have records so load the first record
adoRs.MoveFirst
Do While Not adoRS.EOF
'Process records here
'.
'.
'.
adoRS.MoveNext
Loop
Else
Msgbox "No records returned."
End If
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
I am using .Open to check if record exists.
If it exists, I delete it.
If not, I an adding it.
Then I close the ADODB Recordset.
I am sure there is a better way of doing this - and this is probably a slow way of doing it.
Is there a way of doing this with only one Open and One close?
Here is my code (which is in a Do Loop):
Dim myRecSet As New ADODB.Recordset
Dim strSql As String
strSql = "select * from RentBalances where KeyTcyIdSubAcDate = '" & sKeyTcyIdSubAcDate & "'"
'Display "SQL: " & strSql
myRecSet.Open strSql, SQLSVSExtractConnection, adOpenKeyset, adLockOptimistic
'Display "Total no of records = " & myRecSet.RecordCount
If myRecSet.RecordCount < 1 Then
'Display ("There are no RentBalances record for this ID. ID = " & sKeyTcyIdSubAcDate)
Else
' delete the record
myRecSet.Delete
myRecSet.UpdateBatch
End If
myRecSet.AddNew
myRecSet!KeyTcyIdSubAcDate = rsLocal.Fields("KeyTcyIdSubAcDate")
myRecSet!KeyTcyId = rsLocal.Fields("KeyTcyId")
myRecSet!SubAc = rsLocal.Fields("SubAc")
myRecSet!PeriodEndDate = rsLocal.Fields("PeriodEndDate")
myRecSet!Amount = rsLocal.Fields("Amount")
myRecSet!RentAmount = rsLocal.Fields("RentAmount")
myRecSet!ChargesAmount = rsLocal.Fields("ChargesAmount")
myRecSet!AdjustmentAmount = rsLocal.Fields("AdjustmentAmount")
myRecSet!BenefitAmount = rsLocal.Fields("BenefitAmount")
myRecSet!BenefitBalance = rsLocal.Fields("BenefitBalance")
myRecSet!TenantBalance = rsLocal.Fields("TenantBalance")
myRecSet!PayAmount = rsLocal.Fields("PayAmount")
myRecSet!TimeStamp = rsLocal.Fields("TimeStamp")
myRecSet!UpdateFlag = rsLocal.Fields("UpdateFlag")
myRecSet.Update
myRecCount = myRecCount + 1
myRecSet.Close
The most optimal way of doing this is to bulk insert into a staging table from your code and then call a stored procedure to merge the data from your staging table into your proper table.
'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"
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.