Jump to content

MySQL UDFs (without ODBC)


ProgAndy
 Share

Recommended Posts

@maniootek Sorry, I cannot show the code as its a project of one of my clients!

Anyway, I have already found out the problem, the AV was blocking calls to the DLL!

EasyCodeIt - A cross-platform AutoIt implementation - Fund the development! (GitHub will double your donations for a limited time)

DcodingTheWeb Forum - Follow for updates and Join for discussion

Link to comment
Share on other sites

  • 2 weeks later...

Here we have another strange issue again... Have anyone of you guys experienced a black hole? I mean, not a physical black hole :P, but a internet blackhole

I have a situation where sometimes the selected records don't get received and I get an empty array:

ZxotTno.png

And sometimes the Query which I send to the MySQL server never reaches to it... Also, in both cases NO error was being reported.

EasyCodeIt - A cross-platform AutoIt implementation - Fund the development! (GitHub will double your donations for a limited time)

DcodingTheWeb Forum - Follow for updates and Join for discussion

Link to comment
Share on other sites

Theres a bug in this UDF that needs to be fixed.  If your querying a field, and the field is blank, it gives you zero.  Well what if the field is actually zero?  Theres no way to tell if the field is actually blank, or actually zero.

 

$data = DllStructGetData(DllStructCreate("char[" & $length & "]", $fieldPtr), 1)

should be:

$data = DllStructGetData(DllStructCreate("char[" & $length & "]", $fieldPtr), 1)
            if @error then $data = ""

 

Link to comment
Share on other sites

  • 5 months later...

I am trying to read LONGBLOB data from a remote MySQL db, and then display the retrieved image/pic in an autoIT GUI. Would you have any examples of how to do this?

Briefly, what the below does is insert an image on my c:\ drive to a remote MySQL server. Using MySQL Workbench, I can see the image is stored as a BLOB and that the image looks fine when I open up the BLOB with Workbench.

The next part is where I am having difficulties. I am able to run the select, but clearly, since the data is a BLOB, it does not view properly in the different methods that ProgAndy uses in his included test.au3 file since he is displaying it as a string array. I was wondering what I could do to have the image show up in a very simple autoIT gui?

 

#include <array.au3>
#include <mysql.au3>
dim $file="C:\Users\nickz\Downloads\complexe_Test_SuiviClientLePheonix\images\3281-3281.jpg"
dim $f_handle

_MySQL_InitLibrary()

$MysqlConn = _MySQL_Init()

$connected = _MySQL_Real_Connect($MysqlConn,"host","user","password","dbname")

 If $connected = 0 Then
  $errno = _MySQL_errno($MysqlConn)
  MsgBox(0,"Error:",$errno & @LF & _MySQL_error($MysqlConn))
  If $errno = $CR_UNKNOWN_HOST Then MsgBox(0,"Error:","$CR_UNKNOWN_HOST" & @LF & $CR_UNKNOWN_HOST)
 Endif

$f_handle=FileOpen($file,16)
if @error <> 0 Then
 MsgBox(0,"Error:","file open error " & @error & @CRLF)
EndIf

$contents=FileRead($f_handle,FileGetSize($file))

 if @error <> 0 Then
  MsgBox(0,"Error:","file read error " & @error & @CRLF)
 EndIf
$bmp=String($contents)

;$query="INSERT INTO complexe_Test_SuiviClientLePheonix.tblCLIENTEXTENTION(attachement) values(" & $bmp & ")"
$query="UPDATE `complexe_Test_SuiviClientLePheonix`.`tblCLIENTEXTENTION` SET `attachement`=" & $bmp & " WHERE `NoClient`='3281'"

_MySQL_Real_Query($MysqlConn, $query)
;MsgBox(0,"SQL",$query)

 if @error <> 0 Then
  MsgBox(0,"Error:","SQL statement failed error =" & @error & @CRLF)
 EndIf

;~  address is a blob filed in the database

$query="SELECT attachement from `complexe_Test_SuiviClientLePheonix`.`tblCLIENTEXTENTION` WHERE `NoClient`='3281'"
_MySQL_Real_Query($MysqlConn, $query)
$res = _MySQL_Store_Result($MysqlConn)
msgbox(0,"",$query)

$fields = _MySQL_Num_Fields($res)

$rows = _MySQL_Num_Rows($res)
MsgBox(0, "", $rows & "-" & $fields)
ConsoleWrite("DataType=" & VarGetType($res) & @LF)
ConsoleWrite("DataType=" & VarGetType($fields) & @LF)
ConsoleWrite("DataType=" & VarGetType($rows) & @LF)
; Zugriff 1
MsgBox(0, '', "Zugriff Methode 1- Handarbeit")
Dim $array[$rows][$fields]
For $k = 1 To $rows
    $mysqlrow = _MySQL_Fetch_Row($res,$fields)

    $lenthsStruct = _MySQL_Fetch_Lengths($res)

    For $i = 1 To $fields
        $length = DllStructGetData($lenthsStruct, 1, $i)
        $fieldPtr = DllStructGetData($mysqlrow, 1, $i)
        $data = DllStructGetData(DllStructCreate("char[" & $length & "]", $fieldPtr), 1)
        $array[$k - 1][$i - 1] = $data
    Next
Next
_ArrayDisplay($array)

; Zugriff 2
MsgBox(0, '', "Zugriff Methode 2 - Reihe für Reihe")
_MySQL_Data_Seek($res, 0) ; nur zum zum Zurücksetzen an den Anfang der Abfrage
Do
$row1 = _MySQL_Fetch_Row_StringArray($res)
If @error Then ExitLoop
_ArrayDisplay($row1)
Until @error

MsgBox(0, '', "Zugriff Methode 3 - alles in ein 2D Array")
$array = _MySQL_Fetch_Result_StringArray($res)
_ArrayDisplay($array)

; Feldinformationen
MsgBox(0, '', "Zugriff Feldinformationen")
Dim $arFields[$fields][3]
For $i = 0 To $fields - 1
    $field = _MySQL_Fetch_Field_Direct($res, $i)
    $arFields[$i][0] = _MySQL_Field_ReadValue($field, "name")
    $arFields[$i][1] = _MySQL_Field_ReadValue($field, "table")
    $arFields[$i][2] = _MySQL_Field_ReadValue($field, "db")
Next
_ArrayDisplay($arFields)

; Cleanup
_MySQL_Free_Result($res)

_MySQL_Close($MysqlConn)

_MySQL_EndLibrary()
msgbox(0,"","DONE")
exit(0)

 

Link to comment
Share on other sites

You'd certainly gain from playing with Greencan example:

His code uses SQLite as the DB engine but can obviously be transposed to any ODBC or non-ODBC API.

 

This wonderful site allows debugging and testing regular expressions (many flavors available). An absolute must have in your bookmarks.
Another excellent RegExp tutorial. Don't forget downloading your copy of up-to-date pcretest.exe and pcregrep.exe here
RegExp tutorial: enough to get started
PCRE v8.33 regexp documentation latest available release and currently implemented in AutoIt beta.

SQLitespeed is another feature-rich premier SQLite manager (includes import/export). Well worth a try.
SQLite Expert (freeware Personal Edition or payware Pro version) is a very useful SQLite database manager.
An excellent eBook covering almost every aspect of SQLite3: a must-read for anyone doing serious work.
SQL tutorial (covers "generic" SQL, but most of it applies to SQLite as well)
A work-in-progress SQLite3 tutorial. Don't miss other LxyzTHW pages!
SQLite official website with full documentation (may be newer than the SQLite library that comes standard with AutoIt)

Link to comment
Share on other sites

Hi and thanks for pointing me to that demo. Got it working for that demo in no time. The issue is that it does way more than I actually need and I have spent most of the day trying to convert it from using SQLite to MySQL UDF and I am struggling big time....I can't seem to figure out the portions of this demo that I should be extracting for use and I can't migrate it to MySQL either... :-(

One example is the use of the PRAGMA commands.

I will keep trying here....

Link to comment
Share on other sites

OK. so I am focusing on the _Execbin function. My biggest problem is that when I debug the BLOB to the console in my script compared to the demo, the data returned in mine is only 4 characters in length.

Func _ExecBin($iItem)
    Local $aRow, $iKey, $aResult, $StringRemainder, $sDescription, $hFile, $iMaxRows, $Primary_Key, $sFileextension, $sEndOfFileNameFlag, $aTIFFDimension

    If $bGui_ImageView Then FileDelete($sFileName) ; delete previous file in temp folder

    ; identify Column position of Primary Key
    For $i = 0 To UBound($aNames) - 1 ; every column
        If StringUpper($aNames[$i]) = $sPrimary Then
            $Primary_Key = _GUICtrlListView_GetItemText($hListView, $iItem, $i)
            ExitLoop
        EndIf
    Next

    $Primary_Key = $iItem
    $sPrimary = "NoClient"

    $sSQL = "SELECT Attachement FROM " & $dbname & "." & $sTable & " WHERE " & $sPrimary & "='" & $Primary_Key & "'"
    ConsoleWrite('@@ Debug(' & @ScriptLineNumber & ') : $sSQL = ' & $sSQL & @CRLF & '>Error code: ' & @error & @CRLF) ;### Debug Console
    If $iDebug Then ConsoleWrite(@ScriptLineNumber & " " & $sSQL & @CR)
    $connected = _MySQL_Real_Connect($MysqlConn, $dbhost, $dbuser, $dbpassword, $dbname, $dbport)

    If $connected = 0 Then
        $errno = _MySQL_errno($MysqlConn)
        MsgBox(0, "Erreur:", $errno & @LF & _MySQL_error($MysqlConn))
        If $errno = $CR_UNKNOWN_HOST Then MsgBox(0, "Erreur:", "$CR_UNKNOWN_HOST" & @LF & $CR_UNKNOWN_HOST)
        Exit (0)
    EndIf
    ;;~  attachement is a blob filed in the database
    ;   $noClient = InputBox("Veuillez scanner la carte", "", "", " M10")
    ;   If @error Then _Cleanup()

    Local $mysql_bool = _MySQL_Real_Query($MysqlConn, $sSQL)
    If $mysql_bool = $MYSQL_SUCCESS Then
        ;MsgBox($MB_SYSTEMMODAL, '', "Query OK")
    Else
        $errno = _MySQL_errno($MysqlConn)
        MsgBox($MB_SYSTEMMODAL, "Erreur:", $errno & @LF & _MySQL_error($MysqlConn))
        Return
    EndIf

    ;Local $res2 = _MySQL_Use_Result($MysqlConn)
    ;ConsoleWrite('@@ Debug(' & @ScriptLineNumber & ') : $res2 = ' & $res2 & @CRLF & '>Error code: ' & @error & @CRLF) ;### Debug Console
    Local $res = _MySQL_Store_Result($MysqlConn)
    ConsoleWrite('@@ Debug(' & @ScriptLineNumber & ') : $res = ' & $res & @CRLF & '>Error code: ' & @error & @CRLF) ;### Debug Console
    Local $fields = _MySQL_Num_Fields($res)
    ConsoleWrite('@@ Debug(' & @ScriptLineNumber & ') : $fields = ' & $fields & @CRLF & '>Error code: ' & @error & @CRLF) ;### Debug Console

    Local $rows = _MySQL_Num_Rows($res)
    ConsoleWrite('@@ Debug(' & @ScriptLineNumber & ') : $rows = ' & $rows & @CRLF & '>Error code: ' & @error & @CRLF) ;### Debug Console

    Local $mysqlrow, $lenthsStruct, $length, $fieldPtr, $data
    Local $array[$rows][$fields]

    For $k = 1 To $rows
        $mysqlrow = _MySQL_Fetch_Row($res, $fields)
        ConsoleWrite('@@ Debug(' & @ScriptLineNumber & ') : $mysqlrow = ' & $mysqlrow & @CRLF & '>Error code: ' & @error & @CRLF) ;### Debug Console

        $lenthsStruct = _MySQL_Fetch_Lengths($res)
        ConsoleWrite('@@ Debug(' & @ScriptLineNumber & ') : $lenthsStruct = ' & $lenthsStruct & @CRLF & '>Error code: ' & @error & @CRLF) ;### Debug Console

        For $i = 1 To $fields
            $length = DllStructGetData($lenthsStruct, 1, $i)
            ConsoleWrite('@@ Debug(' & @ScriptLineNumber & ') : $length = ' & $length & @CRLF & '>Error code: ' & @error & @CRLF) ;### Debug Console
            $fieldPtr = DllStructGetData($mysqlrow, 1, $i)
            ConsoleWrite('@@ Debug(' & @ScriptLineNumber & ') : $fieldPtr = ' & $fieldPtr & @CRLF & '>Error code: ' & @error & @CRLF) ;### Debug Console
            $data = DllStructGetData(DllStructCreate("char[" & $length & "]", $fieldPtr), 1)
            ConsoleWrite('@@ Debug(' & @ScriptLineNumber & ') : $data = ' & $data & @CRLF & '>Error code: ' & @error & @CRLF) ;### Debug Console
            $array[$k - 1][$i - 1] = $data
            ConsoleWrite('@@ Debug(' & @ScriptLineNumber & ') : $array = ' & $array[0][0] & @CRLF & '>Error code: ' & @error & @CRLF) ;### Debug Console
        Next
    Next
    _ArrayDisplay($array)

    ;_SQLite_QuerySingleRow(-1, $sSQL, $aRow)
    If @error Then Return SetError(1, 0, @error)

    If $data <> "" Then ; NOT an empty BLOB
        ConsoleWrite('@@ Debug(' & @ScriptLineNumber & ') : $data = ' & $data & @CRLF & '>Error code: ' & @error & @CRLF) ;### Debug Console

 

@@ Debug(326) : $data = ÿØÿà

in the demo its:

@@ Debug(1495) : $aRow[0] = 0x5F5F477265656E43616E2E706E6700FFD8FFE000104A46494600010100000100010000FFDB00840009060614121115141014151 (I have truncated it for the post)

I don't understand the dllstructgetdata command but I think this is where it is failing. I also think there has to be a simpler way to read the 1 record returned as BLOB to $data, but I cannot figure it out...

Link to comment
Share on other sites

I'll have to leave that to someone used to this UDF. I'm not even a MySQL user so I can't give you any good advice here.

This wonderful site allows debugging and testing regular expressions (many flavors available). An absolute must have in your bookmarks.
Another excellent RegExp tutorial. Don't forget downloading your copy of up-to-date pcretest.exe and pcregrep.exe here
RegExp tutorial: enough to get started
PCRE v8.33 regexp documentation latest available release and currently implemented in AutoIt beta.

SQLitespeed is another feature-rich premier SQLite manager (includes import/export). Well worth a try.
SQLite Expert (freeware Personal Edition or payware Pro version) is a very useful SQLite database manager.
An excellent eBook covering almost every aspect of SQLite3: a must-read for anyone doing serious work.
SQL tutorial (covers "generic" SQL, but most of it applies to SQLite as well)
A work-in-progress SQLite3 tutorial. Don't miss other LxyzTHW pages!
SQLite official website with full documentation (may be newer than the SQLite library that comes standard with AutoIt)

Link to comment
Share on other sites

I managed to figure out what was going on. Essentially the dllstruct was of type char instead of byte. Secondly, in the example, there was always a file name within the header with a null character. Since I was not loading the data with the embedded file name with the null character as the blob header, nothing was working.

I am going to clean up the code a bit and post it later. I am super happy this worked...thanks for pointing me to greencans demo.

 

Link to comment
Share on other sites

So the biggest issue I had was understanding the DLLStruct commands. Turned out that I needed to change it from char to byte and as well to upload the files with a proper header that included the filename.

Retrieving and displaying the image can be done with the following (Kudos to GreenCan and others!). Essentially, _Execbin(PK) performs a query and returns the blob based on the clientID which is the Primary key on the table.

Func _DisplayImage($sFile, $sDescription)
    Local $window_open, $aGIFDimension, $iOriginalW, $iOriginalH, $aClientSize, $nScale, $iPosX, $iPosY, $sTip, $iGUIWidth, $iGUIHeigth
    $window_open = WinList("ScanCartes") ; check If window already exists
    If $window_open[0][0] = 0 Then
    Else
        ; window already exist so only change the content
        _GIF_DeleteGIF($hGIF) ; first delete the previous image
        GUICtrlDelete($hGIFLabel) ; and delete the image label
    EndIf

    $aGIFDimension = _GIF_GetDimension($sFile)
    $iOriginalW = $aGIFDimension[0]
    $iOriginalH = $aGIFDimension[1]
    ConsoleWrite('@@ Debug(' & @ScriptLineNumber & ') : $aGIFDimension = ' & $aGIFDimension[0] & "W x " & $aGIFDimension[1] & "H" & @CRLF & '>Error code: ' & @error & @CRLF) ;### Debug Console

    $aClientSize = WinGetClientSize($hGui_ImageView)
    $aClientSize[0] = 220
    $aClientSize[1] = 225
    ConsoleWrite('@@ Debug(' & @ScriptLineNumber & ') : $aClientSize = ' & $aClientSize[0] & "W x " & $aClientSize[1] & "H" & @CRLF & '>Error code: ' & @error & @CRLF) ;### Debug Console
    ; Resize image to fit gui (trancexx)
    $nScale = 1
    While 1
        If $aClientSize[0] - 50 < $aGIFDimension[0] Or $aClientSize[1] - 70 < $aGIFDimension[1] Then
            $nScale /= 1.01
            $aGIFDimension[1] = Round($aGIFDimension[1] * $nScale)
            $aGIFDimension[0] = Round($aGIFDimension[0] * $nScale)
            ConsoleWrite('@@ Debug(' & @ScriptLineNumber & ') : $nScale = ' & $nScale & @CRLF & '>Error code: ' & @error & @CRLF) ;### Debug Console
        Else
            ExitLoop
        EndIf
    WEnd
    While 1
        If $aClientSize[0] - 50 > $aGIFDimension[0] Or $aClientSize[1] - 70 > $aGIFDimension[1] Then
            $nScale *= 1.01
            $aGIFDimension[1] = Round($aGIFDimension[1] * $nScale)
            $aGIFDimension[0] = Round($aGIFDimension[0] * $nScale)
            ConsoleWrite('@@ Debug(' & @ScriptLineNumber & ') : $nScale = ' & $nScale & @CRLF & '>Error code: ' & @error & @CRLF) ;### Debug Console
        Else
            ExitLoop
        EndIf
    WEnd
    ConsoleWrite('@@ Debug(' & @ScriptLineNumber & ') : $aGIFDimension = ' & $aGIFDimension[0] & "W x " & $aGIFDimension[1] & "H" & @CRLF & '>Error code: ' & @error & @CRLF) ;### Debug Console

    $iPosX = (@DesktopWidth - $aGIFDimension[0]) / 2
    $iPosY = 220
    If $iPosY + $aGIFDimension[1] > $aClientSize[1] - 50 Then $iPosY -= $aGIFDimension[1] - $aClientSize[1] + 50 ; not to cover buttons
    $hGIF = _GUICtrlCreateGIF($sFile, "", $iPosX, $iPosY, $aGIFDimension[0], $aGIFDimension[1])
    GUICtrlSetResizing(-1, 768 + 128 + 8 + 32) ; $GUI_DOCKSIZE + $GUI_DOCKVCENTER + $GUI_DOCKHCENTER + $GUI_DOCKTOP
    $sTip = "Size: " & $iOriginalW & " x " & $iOriginalH
    If $nScale < 1 Then $sTip &= @LF & "Resized to fit to: " & $aGIFDimension[0] & " x " & $aGIFDimension[1]
    GUICtrlSetTip($hGIF, $sTip, StringRegExpReplace($sFile, ".*\\", ""), 1)
    $hGIFLabel = GUICtrlCreateLabel($sDescription, 70, $iPosY + $aGIFDimension[1] + 5, @DesktopWidth - 140, 20, 1) ; $SS_CENTER
    GUISetState()

    Return
EndFunc   ;==>_DisplayImage

Func _ExecBin($iItem)
    Local $aResult, $StringRemainder, $sDescription, $hFile, $iMaxRows, $Primary_Key, $sFileextension, $sEndOfFileNameFlag, $aTIFFDimension

    If $bGui_ImageView Then FileDelete($sFileName) ; delete previous file in temp folder

    $Primary_Key = $iItem
    $sPrimary = "NoClient"

    $sSQL = "SELECT Attachement FROM " & $dbname & "." & $sTableClients & " WHERE " & $sPrimary & "='" & $Primary_Key & "'"
    If $iDebug Then ConsoleWrite(@ScriptLineNumber & " " & $sSQL & @CR)
    $connected = _MySQL_Real_Connect($MysqlConn, $dbhost, $dbuser, $dbpassword, $dbname, $dbport)

    If $connected = 0 Then
        $errno = _MySQL_errno($MysqlConn)
        MsgBox(0, "Erreur:", $errno & @LF & _MySQL_error($MysqlConn))
        If $errno = $CR_UNKNOWN_HOST Then MsgBox(0, "Erreur:", "$CR_UNKNOWN_HOST" & @LF & $CR_UNKNOWN_HOST)
        Exit (0)
    EndIf
    ;;~  attachement is a blob filed in the database
    ;   $noClient = InputBox("Veuillez scanner la carte", "", "", " M10")
    ;   If @error Then _Cleanup()

    Local $mysql_bool = _MySQL_Real_Query($MysqlConn, $sSQL)
    If $mysql_bool = $MYSQL_SUCCESS Then
        ;MsgBox($MB_SYSTEMMODAL, '', "Query OK")
    Else
        $errno = _MySQL_errno($MysqlConn)
        MsgBox($MB_SYSTEMMODAL, "Erreur:", $errno & @LF & _MySQL_error($MysqlConn))
        Return
    EndIf

    Local $res = _MySQL_Store_Result($MysqlConn)
    Local $fields = _MySQL_Num_Fields($res)
    Local $rows = _MySQL_Num_Rows($res)

    Local $mysqlrow, $lenthsStruct, $length, $fieldPtr, $data

    If $rows > 0 Then
        For $k = 1 To $rows
            $mysqlrow = _MySQL_Fetch_Row($res, $fields)
            $lenthsStruct = _MySQL_Fetch_Lengths($res)
            For $i = 1 To $fields
                $length = DllStructGetData($lenthsStruct, 1, $i)
                $fieldPtr = DllStructGetData($mysqlrow, 1, $i)
                $data = DllStructGetData(DllStructCreate("byte[" & $length & "]", $fieldPtr), 1)
            Next
        Next
    EndIf
    If $data <> "" Then ; NOT an empty BLOB
        If $bBlobRaw Then
            ; $aRow[0] = $aRow[0]  ; raw BLOB
            If StringMid($data, 3, 8) == "89504E47" Then ; png file signature
                $sFileextension = "png"
                $sFileName = _TempFile(@TempDir, "~", "." & $sFileextension)
                $sFileName = StringRight($sFileName, StringLen($sFileName) - StringInStr($sFileName, "\", 0, -1)) ; split filename from path
            ElseIf StringMid($data, 3, 4) == "424D" Then ; bmp file signature 424D
                $sFileextension = "bmp"
                $sFileName = _TempFile(@TempDir, "~", "." & $sFileextension)
                $sFileName = StringRight($sFileName, StringLen($sFileName) - StringInStr($sFileName, "\", 0, -1)) ; split filename from path
            ElseIf StringMid($data, 15, 8) == "4A464946" Then ; jpg file signature 4A464946
                $sFileextension = "jpg"
                $sFileName = _TempFile(@TempDir, "~", "." & $sFileextension)
                $sFileName = StringRight($sFileName, StringLen($sFileName) - StringInStr($sFileName, "\", 0, -1)) ; split filename from path
            ElseIf StringMid($data, 3, 6) == "474946" Then ; gif file signature 474946
                $sFileextension = "gif"
                $sFileName = _TempFile(@TempDir, "~", "." & $sFileextension)
                $sFileName = StringRight($sFileName, StringLen($sFileName) - StringInStr($sFileName, "\", 0, -1)) ; split filename from path
            ElseIf StringMid($data, 3, 8) == "00000100" Then ; ico file signature 00000100
                $sFileextension = "ico"
                $sFileName = _TempFile(@TempDir, "~", "." & $sFileextension)
                $sFileName = StringRight($sFileName, StringLen($sFileName) - StringInStr($sFileName, "\", 0, -1)) ; split filename from path
            ElseIf StringMid($data, 3, 8) == "49492A00" Then ; tif file Intel byte order signature 49492A00
                $sFileextension = "tif"
                $sFileName = _TempFile(@TempDir, "~", "." & $sFileextension)
                $sFileName = StringRight($sFileName, StringLen($sFileName) - StringInStr($sFileName, "\", 0, -1)) ; split filename from path
            ElseIf StringMid($data, 3, 8) == "4D4D002A" Then ; tif file Motorola byte order signature 4D4D002A
                $sFileextension = "tif"
                $sFileName = _TempFile(@TempDir, "~", "." & $sFileextension)
                $sFileName = StringRight($sFileName, StringLen($sFileName) - StringInStr($sFileName, "\", 0, -1)) ; split filename from path
            Else
                ; unknown format
                MsgBox(48, "Cannot View", "Sorry, the object cannot be recognized as an image", 3) ; not an error
                Return 1
            EndIf
        Else
            ; split file name and BLOB object
            ;$sEndOfFileNameFlag = StringInStr($aRow[0], "00")
            $sEndOfFileNameFlag = StringInStr($data, "00")
            If Int($sEndOfFileNameFlag / 2) = $sEndOfFileNameFlag / 2 Then $sEndOfFileNameFlag += 1
            ;$sFileName = BinaryToString(StringLeft($aRow[0], $sEndOfFileNameFlag - 1))
            $sFileName = BinaryToString(StringLeft($data, $sEndOfFileNameFlag - 1))
            If @error Then Return SetError(2, 0, @error)
            ;$aRow[0] = "0x" & StringTrimLeft($aRow[0], $sEndOfFileNameFlag + 1)
            $data = "0x" & StringTrimLeft($data, $sEndOfFileNameFlag + 1)
            $sFileextension = StringTrimLeft($sFileName, StringInStr($sFileName, "."))
        EndIf
        $aResult = StringRegExp($data, "(.{4094}|.{1,4094)", 3)
        $StringRemainder = StringTrimLeft($data, Int(StringLen($data) / 4094) * 4094)

        ; Currently, I display the file name of raw objects starting with a tilde ~
;~      If $bBlobRaw Then
;~          $sDescription = ""
;~      Else
        $sDescription = $sFileName
;~      EndIf

        If StringInStr(".gif;.png;.jpg;.tif;.bmp;.jpeg;.ico;", $sFileextension) > 0 Then
            $sFileName = @TempDir & "\" & $sFileName
        Else
            ; create executable objects in export folder
            $sFileName = $sExportFolder & "\" & $sFileName
        EndIf

        ; create object
        $hFile = FileOpen($sFileName, 16 + 2)
        If @error Then Return SetError(3, 0, 0)
        $iMaxRows = UBound($aResult)
        If $iMaxRows = 0 Then ; BLOB contains less than 4094 bytes
            FileWrite($hFile, $StringRemainder)
        Else
            FileWrite($hFile, $aResult[0]) ; "0x" already exists for the first row
            For $ii = 1 To $iMaxRows - 1
                FileWrite($hFile, "0x" & $aResult[$ii])
            Next
            FileWrite($hFile, "0x" & $StringRemainder)
        EndIf
        FileClose($hFile)
        If StringInStr(".gif;.png;.jpg;.bmp;.jpeg;.ico;", $sFileextension) > 0 Then

            _DisplayImage($sFileName, $sName)
        ElseIf StringInStr(".tiff;.tif;", $sFileextension) > 0 Then
            ; convert the tiff files to bmp, so that multipage tiff display the first page in the viewer
            ; it might be preferable to execute the multipage tiff so that it is displayed properly but
            ; I have no method to differentiate multipage from single page tiff...
            $aTIFFDimension = _GIF_GetDimension($sFileName)
            _ImageResize($sFileName, StringLeft($sFileName, StringInStr($sFileName, ".", 0, -1) - 0) & "bmp", $aTIFFDimension[0], $aTIFFDimension[1])
            _DisplayImage(StringLeft($sFileName, StringInStr($sFileName, ".", 0, -1) - 0) & "bmp", $sDescription)
            FileDelete(StringLeft($sFileName, StringInStr($sFileName, ".", 0, -1) - 0) & "bmp") ; delete the temporary file
        Else
            If $bGui_ImageView Then
                FileDelete($sFileName) ; delete last image file in temp folder
                GUIDelete($hGui_ImageView)
                $bGui_ImageView = False
            EndIf
            ToolTip("Executing...", MouseGetPos(0) + 20, MouseGetPos(1) + 20)
            ShellExecute($sFileName, "", @ScriptDir)
            ; just don't know how to export (move to @scriptdir on request) these files yet, so I don't delete the objects
            ; and I cannot delete here unless I ShellExecuteWait of course
            ToolTip("")
        EndIf
    Else
        ;MsgBox(0, "NOBLOB", "No Image Found, show default image")
        ;If Not FileExists(@ScriptDir & "\Resources\_DefaultImage.jpg") Then _Create_resources()
        _DisplayImage(@ScriptDir & "\Resources\_DefaultImage.jpg", "Photo non trouvée")
    EndIf

    Return 1
EndFunc   ;==>_ExecBin

And to load the BLOB data into MySQL, it will store the BLOB data along with the proper filename in the header for retrieval into a LONGBLOB field called Attachement:

#Region ;**** Directives created by AutoIt3Wrapper_GUI ****
#AutoIt3Wrapper_Res_Comment=imgUploader to store images to a MySQL DB as BLOB
#AutoIt3Wrapper_Res_Description=imgUploader to store images to a MySQL DB as BLOB
#AutoIt3Wrapper_Res_Fileversion=1.0.0.6
#AutoIt3Wrapper_Res_Fileversion_AutoIncrement=y
;#AutoIt3Wrapper_AU3Check_Parameters=-d -w 1 -w 2 -w 3 -w 4 -w 5 -w 6 -w 7
#AutoIt3Wrapper_AU3Check_Parameters=-d -w 1 -w 2 -w 3 -w 4 -w 6 -w 7
#AutoIt3Wrapper_Run_Tidy=y
#Tidy_Parameters=/sort_funcs /reel
#EndRegion ;**** Directives created by AutoIt3Wrapper_GUI ****
#include <array.au3>
#include <mysql.au3>
#include <libMySQLdll.au3>
#include <File.au3>
#include <MsgBoxConstants.au3>

Opt('MustDeclareVars', 1)

Global $sExtFilter = "bmp|gif|jpeg|jpg|png|tif|tiff"
Global $hTimer, $fDiff, $MysqlConn
Global $connected, $errno, $dbhost, $dbuser, $dbpassword, $dbname, $dbport

$dbhost = InputBox("DB Host", "Please enter the dbhost name (i.e. www.xyz.com, localhost)")
If @error Then Exit (0)
$dbuser = InputBox("DB User", "Please enter the dbuser name (i.e. sa)")
If @error Then Exit (0)
$dbpassword = InputBox("DB User Password", "Please enter the password for: <" & $dbuser & ">", "", "*")
If @error Then Exit (0)
$dbname = InputBox("DB Name", "Please enter the db name (i.e. xyz_DBName)")
If @error Then Exit (0)
$dbport = InputBox("DB Port", "Please enter the db port for MySQL (typically 3306)", "3306")
If @error Then Exit (0)

_MySQL_InitLibrary()

$MysqlConn = _MySQL_Init()

$connected = _MySQL_Real_Connect($MysqlConn, $dbhost, $dbuser, $dbpassword, $dbname, $dbport)

If $connected = 0 Then
    $errno = _MySQL_errno($MysqlConn)
    MsgBox(0, "Error:", $errno & @LF & _MySQL_error($MysqlConn))
    If $errno = $CR_UNKNOWN_HOST Then MsgBox(0, "Error:", "$CR_UNKNOWN_HOST" & @LF & $CR_UNKNOWN_HOST)
    Exit (0)
EndIf

_Browse()

; Cleanup
_MySQL_Close($MysqlConn)

_MySQL_EndLibrary()
$fDiff = TimerDiff($hTimer) ; Find the difference in time from the previous call of TimerInit. The variable we stored the TimerInit handlem is passed as the "handle" to TimerDiff.
MsgBox($MB_SYSTEMMODAL, "DONE", "DONE. Total upload time = " & Round($fDiff / 1000, 0) & " seconds")
Exit (0)

Func _Browse()
    Local $FSF, $FL2A, $iCnt = 0
    $FSF = FileSelectFolder("Browse for folder containing pictures", "C:", "C:\LLN")
    If Not @error And FileExists($FSF) Then
        If StringRight($FSF, 1) <> "\" Then $FSF &= "\"
        $FL2A = _FileListToArray($FSF, "*", 1)
        ;ConsoleWrite($FSF)
        ;ConsoleWrite(_ArrayDisplay($FL2A, "List of Files"))
        If Not @error Then
            ;ConsoleWrite("NO ERROR after fl2a")
            $hTimer = TimerInit() ; Begin the timer and store the handle in a variable.
            ; Display a progress bar window.
            ProgressOn("Progress Meter", "Images uploading...", "0%")
            ; Update the progress value of the progress bar window every second.
            For $i = 1 To $FL2A[0]
                If StringRegExp($FL2A[$i], "(?i)\.(" & $sExtFilter & ")", 0) Then
                    ConsoleWrite("Uploading:" & $FSF & $FL2A[$i] & @CRLF)
                    _uploadImage($FSF & $FL2A[$i], $FL2A[$i])
                    ProgressSet((Round($i / $FL2A[0] * 100, 0)), (Round($i / $FL2A[0] * 100, 0)) & "%")
                    $iCnt += 1
                EndIf
            Next
        EndIf
    EndIf
    ; Set the "subtext" and "maintext" of the progress bar window.
    ProgressSet(100, "Done", "Complete")
    Sleep(5000)
    ; Close the progress window.
    ProgressOff()
    MsgBox($MB_SYSTEMMODAL, "", "Images Processed: " & $iCnt, 10)
EndFunc   ;==>_Browse

Func _uploadImage($file, $fname)

    Local $f_handle, $contents, $bmp, $query, $mysql_bool
    Local $iPosition = StringInStr($fname, "-")
    ;ConsoleWrite("iPosition=" & $iPosition & @CRLF)

    If $iPosition > 0 Then
        Local $noClient = StringMid($fname, 1, $iPosition - 1)
        ConsoleWrite("NoClient=" & $noClient & @CRLF)
        $f_handle = FileOpen($file, 16)
        If @error <> 0 Then
            MsgBox($MB_SYSTEMMODAL, "Error:", "file open error " & @error & @CRLF)
        EndIf

        $contents = FileRead($f_handle, FileGetSize($file))

        If @error <> 0 Then
            MsgBox($MB_SYSTEMMODAL, "Error:", "file read error " & @error & @CRLF)
        EndIf
        ;(Binary($sFileName & Chr(0) & BinaryToString($sBinaryString)))
        ;Filename plus null chr(0) so that the retrieval can be done
        $bmp = String(StringToBinary($fname & Chr(0)) & $contents)

        ;$query="INSERT INTO complexe_Test_SuiviClientLePheonix.tblCLIENTEXTENTION(attachement) values(" & $bmp & ")"
        $query = "UPDATE `" & $dbname & "`.`tblCLIENTEXTENTION` SET `attachement`=" & $bmp & " WHERE `NoClient`='" & $noClient & "'"
        ;ConsoleWrite("UPDATE `" & $dbname & "`.`tblCLIENTEXTENTION` SET `attachement`=" & "$bmp" & " WHERE `NoClient`='" & $noClient & "'" & @CRLF & @CRLF)
        ;MsgBox(0, "SQL", $query)

        $mysql_bool = _MySQL_Real_Query($MysqlConn, $query)
        If $mysql_bool = $MYSQL_SUCCESS Then
            ;MsgBox($MB_SYSTEMMODAL, '', "Query OK")
        Else
            $errno = _MySQL_errno($MysqlConn)
            MsgBox($MB_SYSTEMMODAL, "Error:", $errno & @LF & _MySQL_error($MysqlConn))
        EndIf
    EndIf
EndFunc   ;==>_uploadImage

 

Hope this helps others.

Link to comment
Share on other sites

  • 3 months later...
5 hours ago, Tomy46 said:

Hello everyone !

Unless I'm mistaken, I can not find the function" _MySQL_Real_Query" in mysql.au3 of ProgAndy ...

Can you help me ?

Thank you.

post a location you got it from

I checked in my MySQL.au3 file and _MySQL_Real_Query is located in 1555 line

real.JPG

Link to comment
Share on other sites

  • 10 months later...

Hello everyone.

 

I have a problem with "Error: 2006 MySQL server has gone away".

Because i want to send a binary data of a big picture to the MYSQL server.

I have read the documentation of mysql "https://dev.mysql.com/doc/refman/8.0/en/gone-away.html".

Maybe I think the issue is that the max_allowed_packet is too small.

20180515113504.thumb.jpg.c2cd051fad28eba7678a8ee69b7016f2.jpg

I didn't know how to set the value of max_allowed_packet on the client side.

Please help me thx.

Link to comment
Share on other sites

6 minutes ago, TheDcoder said:

@Xwolf You cannot modify server configuration from client side

@TheDcoder

In fact, I can modify the set from remote MySQLServer throught browser.

And i checked the set of server side, the value is 1073741824.

Now i want to modify the value of the client side.

Link to comment
Share on other sites

1 hour ago, Xwolf said:

In fact, I can modify the set from remote MySQLServer throught browser.

Well, modifying it from the browser is different from doing it via an SQL connection :)

1 hour ago, Xwolf said:

And i checked the set of server side, the value is 1073741824.

Now i want to modify the value of the client side.

If the value on the server side is greater than what you want, then it is enough, you don't have to modify anything on the client side to make this work. However, seeing how the server is still disconnecting, there might be some other setting or 3rd party software on the server which is preventing the connection transfer large amounts of data.

I recommend you check the server and see if everything is in place, look for configurations which might be over-riding the 1 GB limit.

Edited by TheDcoder

EasyCodeIt - A cross-platform AutoIt implementation - Fund the development! (GitHub will double your donations for a limited time)

DcodingTheWeb Forum - Follow for updates and Join for discussion

Link to comment
Share on other sites

42 minutes ago, TheDcoder said:

Well, modifying it from the browser is different from doing it via an SQL connection :)

If the value on the server side is greater than what you want, then it is enough, you don't have to modify anything on the client side to make this work. However, seeing how the server is still disconnecting, there might be some other setting or 3rd party software on the server which is preventing the connection transfer large amounts of data.

I recommend you check the server and see if everything is in place, look for configurations which might be over-riding the 1 GB limit.

OK

I will do that what you say.

Thank you very much.

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...