Sign in to follow this  
Followers 0
sivaramanm

Unable to retrieve inserted row count in MySQL using ADO from AutoIT

7 posts in this topic

#1 ·  Posted (edited)

From AutoIT script (Pretty much same syntax as VBA), Tried connecting to MySQL Server. While i am able to insert a new row successfully, unable to verify the rowcount (# of inserted row - to verify success or failure).

Have tried two different methods -

  1. to use the RecordsAffected variable from Connection Execute function
  2. to use the RecordSet and retrieve the rowcount

But have been missing something and none of these methods return the actual row count.

Any help would be appreciated.!!!

Cross-posted in http://stackoverflow.com/questions/27411599/unable-to-retrieve-inserted-row-count-in-mysql-using-ado-from-autoit

MySQLConnect()

$EVENT_TIME= "2014-12-12 12:12:12"
$LSMCName='LSMC1'
$NEType='MME0001'
$OMTarFile='A_MME0011-60MIN-20141212-12-v.tar'
$CSVFile='12-00-S1AP.csv'
$KPIType='S1AP_HO'
$UpdateStatus='NotUpdated'
$ReTries='0'

If Not (InsertFileUpdateLog($EVENT_TIME,$LSMCName,$NEType,$OMTarFile,$CSVFile,$KPIType,$UpdateStatus,$ReTries)=1) Then
WriteLog("[Error] Record insertion failed for " & $EVENT_TIME & '" ' & $LSMCName & ' ' & $NEType & ' ' & $OMTarFile & ' ' & $CSVFile & ' ' & $KPIType & ' ' & ' NotUpdated 0')
EndIf
MysqlDisconnect()

;~ ####################### Sub Function Definitions

Func MySQLConnect()
Local $sDriver="MySQL ODBC 5.3 ANSI Driver"
Local $key = "HKEY_LOCAL_MACHINE\SOFTWARE\ODBC\ODBCINST.INI\ODBC Drivers", $val = RegRead($key, $sDriver)
If @error or $val = "" Then
SetError(2)
Return -1
EndIf

$constrim="DRIVER={MySQL ODBC 5.3 ANSI Driver};SERVER=localhost;DATABASE=pmdemo;uid=rootuser;pwd=rootpass;"
$oDBConnect = ObjCreate ("ADODB.Connection") ; <== Create SQL connection
$oDBConnect.Open ($constrim) ; <== Connect with required credentials

if @error Then
WriteLog("[Error] Failed to connect to the database")
SetError(2)
Return -2
Else
;MsgBox(0, "Success!", "Connection to database successful!")
Return 1
EndIf
EndFunc

Func MySQLDisConnect()
$oDBConnect.Close ; ==> Close the database
EndFunc

Func InsertFileUpdateLog($EVENT_TIME,$LSMCName,$NEType,$OMTarFile,$CSVFile,$KPIType,$UpdateStatus,$ReTries)
Local $RowCount = 0
Local $result = ObjCreate("ADODB.Recordset")

$sQuery = "INSERT INTO 4gc_fileupdatelog (id,EVENT_TIME,LSMC,NEType,TarFile,CSVFile,KPIFile,UpdateStatus,ReTries) VALUES ('0'," & _
"'" & $EVENT_TIME & "'," & _
"'" & $LSMCName & "'," & _
"'" & $NEType & "'," & _

"'" & $OMTarFile & "'," & _
"'" & $CSVFile & "'," & _
"'" & $KPIType & "'," & _
"'" & $UpdateStatus & "'," & _
"'" & $ReTries & "'" & _
") ON DUPLICATE KEY UPDATE ReTries=ReTries+1,UpdateStatus='" & $UpdateStatus & "';"

$result = $oDBConnect.Execute($sQuery,$RowCount)
If @error Then
MsgBox(1,1,"Error executing query...")
Return -2
EndIf

;# Method-1 : To use records affected from Execute function
If $RowCount >= 1 Then
MsgBox(1,1,"Success")
Else
MsgBox(1,1,"Failed, rowcount is:" & $RowCount )
EndIf

If Not ($result.bof AND $result.eof) Then
WriteLog("[Error] No Rows found")
Return 0
EndIf

;# Method-2 : To use recordsset object and retrieve the rows/columns count
If IsObj($result) And $result.EOF=False Then
$myarray=$result.GetRows()
$rows = UBound($myarray,1)
$cols = UBound($myarray,2)
MsgBox(1,1," rows: " & $rows & " cols: " & $cols)

If ($rows = 1) Then
WriteLog("[Info] Record inserted successfully")
Return 1
ElseIf ($rows = 2) Then
WriteLog("[Alert] Record updated successfully. affected row(s) is " & $rows)
Return $rows
Else

> Blockquote

WriteLog("[Error] Record insertion failed. affected row(s) is " & $rows)
Return 0
EndIf
EndIf

EndFunc
Edited by sivaramanm

Share this post


Link to post
Share on other sites



#2 ·  Posted (edited)

I had almost the same problem, Rowcount and shit didnt work, no matter what I tried.
When you do an .GetRows on your executed statement, you will get a 2-dimensional array back.

UBound($Array) gets you the # of rows

UBound($Array, 2) gets you the # of columns

I ended up using this method since it would give me the same result as rowcount would.

Edited by Radiance

Share this post


Link to post
Share on other sites

#3 ·  Posted (edited)

Thanks for that info. But as mentioned in my post, i am trying that GetRows option also.

That doesnt work either. PFA the error im getting.

BTW as i said, i am trying to insert a new row. Did GetRows work for you for an insert statement? if so would you mind sharing the code to cross check if i am missing anything?

Appreciate your help!

post-79561-0-89296800-1418324502_thumb.j

Edited by sivaramanm

Share this post


Link to post
Share on other sites

Oh, I misread that. I thought you were going to do a select.

>This here is your problem, isn't it?

Share this post


Link to post
Share on other sites

Pretty much yes, except that im trying to do an "insert into table... on duplicate key update " query which means it can be 1 inserted or 2 rows updated. And thats the value what i wanted to check for.

P.S. To be more specific - in this situation, row count will return 1 if a row was inserted, 2 if a row was updated and 0 if it was an identical match to an existing record (so neither insert nor update).

Share this post


Link to post
Share on other sites

The only solution I came up with for this is to do a SELECT right after your INSERT/UPDATE to check if the table contains the data you expected.

Share this post


Link to post
Share on other sites

#7 ·  Posted (edited)

I don't have enough knowledge of MySQL capabilities/bugs but maybe there exists something similar to SQLite's sqlite3_changes() which returns the number of DB changes within the last terminated statement over the current DB connection.

Edited by jchd
1 person likes this

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)

Share this post


Link to post
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
Sign in to follow this  
Followers 0

  • Similar Content

    • Fhelipe
      By Fhelipe
      Nothing More
    • rynow
      By rynow
      romaSQL
      This autoIt UDF is built on the concept of Laravel Query & doctrine.
      RomaSQL provides a new, comfortable and easy to use way for SQL-queries in autoIt.
      Most of the common SQL-queries are supported already and more are coming soon.
      All of your support is much appreciated.
      Connections
      For the connection the object ADODB is used. Therefore the connection string is based on ODBC.
      You can also use OLEDB connection strings or other database connections.
      In order for this to work your add-ons have to be installed in the function: __4ern_SQL_Connection.
      I’d be very glad if you shared your modifications with me.
      Currently supported connections
      -       MySQL (odbc)
      -       Microsoft SQL Server (odbc)
      -       SQLite (odbc)
      -       Microsoft Access (odbc)
      Command reference
      $SQL_connect; establishing connection $SQL_returnType; return a Array or Dictionary ('oDict') Object (Default = Array) $SQL_setDefaultTable; Default Tablename $SQL_setDefaultKey; Default Colmn Key (Default = id) $SQL_debug; if True, show SQL Statment in Console $SQL_get $SQL_update $SQL_delete $SQL_insertInto $SQL_take $SQL_limit $SQL_table $SQL_select $SQL_distinct $SQL_where $SQL_orWhere $SQL_whereBetween $SQL_whereNotBetween $SQL_whereIn $SQL_whereNotIn $SQL_whereNull $SQL_whereNotNull $SQL_having $SQL_orHaving $SQL_havingBetween $SQL_havingNotBetween $SQL_havingIn $SQL_havingNotIn $SQL_havingNull $SQL_havingNotNull $SQL_groupBy $SQL_orderBy  
      Examples
      establishing connection
      ;-----/ ; SQLite Connection ;-----/ $SQL_setDatabase('sqlite') $SQL_connect('C:\project.db') ;-----/ ; Access Connection ; Database, User, Password ;-----/ $SQL_setDatabase('access') $SQL_connect('C:\project.mdb') ;or as Admin $SQL_connect('C:\project.mdb', '4ern', 'root') ;-----/ ; SQLServer Connection ; Database, User, Password, Server, Driver ;-----/ $SQL_setDatabase('sqlserver') $SQL_connect('myDB', '4ern', 'root', 'localhost') ;or with Driver $SQL_connect('myDB', '4ern', 'root', 'localhost', 'SQL Server') ;-----/ ; MySQL Connection ; Database, User, Password, Server, Driver ;-----/ $SQL_setDatabase('mysql') $SQL_connect('myDB', '4ern', 'root', 'localhost') ;or with Driver $SQL_connect('myDB', '4ern', 'root', 'localhost', 'MySQL ODBC 5.2 UNICODE Driver')  
      simple SQL query
      $SQL_table('albums') $aRet = $SQL_get() if IsArray($aRet ) then _ArrayDisplay($aRet ) else ConsoleWrite('Keine Ergebnisse' & @LF) endif  
      Select
      $SQL_table('albums') $SQL_select('id', 'Name', 'Artist', 'Song') ;or pass to an Array Local $aSelect = ['id', 'Name', 'Artist', 'Song'] $SQL_select($aSelect) $aRet = $SQL_get() if IsArray($aRet ) then _ArrayDisplay($aRet ) else ConsoleWrite('Keine Ergebnisse' & @LF) endif where
      $SQL_table('albums') $SQL_select('id', 'Name', 'Artist', 'Song', 'Votes') $SQL_where('Artist', 'adele') $SQL_where('Votes', '>=' ,'9') $SQL_orWhere('Artist', '=' ,'Rag'n'Bone Man') ;or pass to an 2dArray Local $aSelect = [['Artist','adele'],['Votes', '>=' ,'9']] $SQL_where($aSelect) $aRet = $SQL_get() if IsArray($aRet ) then _ArrayDisplay($aRet ) else ConsoleWrite('Keine Ergebnisse' & @LF) endif  
      If you need more examples, then tell me exactly what you need.
      I hope you like my UDF and find some use for it.
      ---
      ->DONWLOAD romaSQL
       
       
    • macran
      By macran
      I use mysql.au3 to connect mysql database .  If restart the server ,the client how to reconnect mysql?
      The function prototype is
      _MySQL_Options($MySQL_ptr, $option, $arg = 0, $type = "ptr")
      so,
      _MySQL_Options($MysqlConn,$MYSQL_OPT_RECONNECT, ?, ?)
      pls help me,thanks!
       
       
       
    • Omega19
      By Omega19
      Hello together,
       
      I need to write just one line into a file. The file is generated by an other program and contains some information first and afterwards a PDF-file. FileGetEncoding results in 16 (Binary), and it containes @CRLF, @CR and @LF, which need to stay right where they are. The best results I got so far were _FileWriteToLine, which replaced every  @LF and @CR with @CRLF and destroyed the PDF inside of my file. So the line was added but the file got unusable.
      I read the following thread

      and made my own example to fit my problem, but they doesn't seem to work:
      $sFileName = "test.txt" prepareFile($sFileName) ;Local $result = FileWriteAtLine($sFileName,"Add in line 3",3) Local $result = FileWriteAfter($sFileName,"Add in line 3","line3") If $result = 1 Then ConsoleWrite("That seems to work." & @CRLF) Else ConsoleWrite("That didn't work. Read lines: " & -$result & @CRLF) EndIf Exit Func prepareFile($sFileName) FileWrite($sFileName, "") $hFile = FileOpen($sFileName,2+16) FileWrite($hFile,"line1" & @CRLF & "line2" & @CRLF & "line3" & @CRLF & "line4" & @CRLF & "line5" & @CRLF & "etc" & @LF & "etc" & @CR & "etc" & @CR & "etc" & @LF & "etc" & @CRLF) FileFlush($hFile) FileClose($hFile) EndFunc Func FileWriteAtLine($sFileName,$sLine,$iLine) $linecount = 0 Local $iEncoding = FileGetEncoding($sFileName,2) ConsoleWrite("Encoding: " &$iEncoding & @CRLF ) $iEncoding = 16 Local $sTempName = "tempfile.tmp" $file = FileOpen($sFileName, $iEncoding) ; Check if file opened for reading OK If $file = -1 Then MsgBox(0, "Error", "Unable to open file.") Exit EndIf Local $sBuffer = FileRead($file,FileGetSize($sFileName)) If @error = -1 Then ConsoleWrite("CANNOT READ" & @CRLF) FileClose($file) ConsoleWrite($sBuffer) ; Read in lines of text until the EOF is reached FileWrite($sTempName,"") Local $hTempfile = FileOpen($sTempName,1 + $iEncoding) $iResult = 1 While 1 Local $iZeichen = StringInStr($sBuffer, @CRLF) If $iZeichen > 0 Then $linecount += 1 If $linecount = $iLine Then FileWrite($hTempfile,$sLine) FileWrite($hTempfile,$sBuffer);Write everything else ExitLoop EndIf Local $line = StringLeft($sBuffer,$iZeichen + 1) $sBuffer = StringTrimLeft($sBuffer, $iZeichen +1) FileWrite($hTempfile,$line) ;FileFlush($hTempfile) Else FileWrite($hTempfile,$sBuffer);Write everything else $iResult = -$linecount ExitLoop EndIf Wend FileClose($hTempfile) FileMove($sTempName,$sFileName,1) Return $iResult EndFunc Func FileWriteAfter($sFileName,$sLine,$sAfter) $linecount = 0 Local $iEncoding = FileGetEncoding($sFileName,2) ConsoleWrite("Encoding: " &$iEncoding & @CRLF ) $iEncoding = 16 Local $sTempName = "tempfile.tmp" $file = FileOpen($sFileName, $iEncoding) ; Check if file opened for reading OK If $file = -1 Then MsgBox(0, "Error", "Unable to open file.") Exit EndIf Local $sBuffer = FileRead($file,FileGetSize($sFileName)) If @error = -1 Then ConsoleWrite("CANNOT READ" & @CRLF) FileClose($file) ConsoleWrite($sBuffer) ; Read in lines of text until the EOF is reached FileWrite($sTempName,"") Local $hTempfile = FileOpen($sTempName,1 + $iEncoding) $iResult = 1 Local $iZeichen = StringInStr($sBuffer,$sAfter) If $iZeichen > 0 Then Local $sFirst = StringLeft($sBuffer,$iZeichen + StringLen($sAfter)) $sBuffer = StringTrimLeft($sBuffer, $iZeichen + StringLen($sAfter)) FileWrite($hTempfile,$sFirst) FileWrite($hTempfile,$sLine) FileWrite($hTempfile,$sBuffer) Else FileWrite($hTempfile,$sBuffer);Write everything else $iResult = $linecount EndIf FileClose($hTempfile) FileMove($sTempName,$sFileName,1) Return $iResult EndFunc Both function result in 0, so my string or the  @CRLF cannot be found inside of the buffer.
       
      What's my mistake?
       
      Thanks,
      Omega19
    • tarretarretarre
      By tarretarretarre
      Now its my turn to give back to the community ( Better late than never :P)..
       
      First i want to thank progAndy for his amazing UDF which this idea came from

       
      And the AutoitObject Team (For making autoit fun again)
       

      I dont have so much to say more thant to let the project speak for itself, ive had this for a couple of months but it was "integrated" into my own "framework" but today I decided to release it because i have seen some people on the forum search for something like this.
      What libraries does this use and are they included?
      Connector/C 6.1.6 ( https://dev.mysql.com/downloads/connector/c/ ) And yes, they are included in the download so nothing has to be installed or anything

      What are the features:
      Prepared statements 32 and 64 bit environment Multiline prepared statements  Simplicity User-friendly PDO-like Syntax & Methods (http://php.net/pdo)  
      So whats the difference between this and x's Mysql UDF?
      When you are fetching your data from your database, you use your table-names to display them, like this:
      with $MySql Local $Vars = ["?", $lastname, "?", $age] .prepare("SELECT id, surname, lastname FROM users WHERE lastname = ? AND AGE > ?") .execute($Vars) Consolewrite(stringformat("Searchresult: %d Hits", .rowCount()) for $row in $oRows consolewrite("Surname: " & $row.surname & @crlf) consolewrite("Lastname: " & $row.lastname & @crlf) next endwith  
      Function-list (Yeah i might improve this when i have time)
      ; Every parameter is a default value of method _miniSQL_setDllDir(@ScriptDir); returns nothing Local Const $MySql = _miniSQL_LoadLibrary(); Returns object with methods ; Starts the library, connects to the database and returns the object $MySql.Startup($sHost, $sUser, $sPass = "", $sDatabase = "", $iPort = 0, $sUnix_socket = "", $iClient_Flag = 0); Returns TRUE if connection was succeded otherwise FALSE ; Shuts down the library and prevents any methods to be executed $MySql.Shutdown() ; The desired SQL query goes here (SELECT x FROM table) $MySql.prepare($sQuery); Returns nothing ; Used for multi-line prepared statements (See Example3 - newline prepared statements) $MySql.PrepareGlue($sQuery); Returns nothing ; Cleans any previous prepared statement of any kind $MySql.PrepareClean(); Returns nothing ; Executes a prepared statement of any kind, with or without passed arguments $MySql.execute($aVars = Null, $iExecuteStyle = $_miniSQL_ExecuteStoreResult); returns TRUE if success, otherwise FALSE ; Options for $iExecuteStyle: $_miniSQL_ExecuteStoreResult = 0 and $_miniSQL_ExecuteOnly = 1 ; Fetches previous executed prepared statement (If anything was stored "see Options for iExecuteStyle") $MySql.fetchAll($iFetchStyle = $_miniSQL_FetchObject); Returns (Depends on $iFetchStyle) ; Options for $iFetchStyle: $_miniSQL_FetchObject = 0 (Default), $_miniSQL_FetchSingleObject = 1, $_miniSQL_FetchArray = 2, $_miniSQL_FetchSingleValue = 3 ; Gives you the "lastinsertId" (The last id that was affected) $MySql.lastInsertId(); Returns the last affected id ; Counts the affected rows done by any MySQL operation (INSERT\SELECT\UPDATE\DELETE) $MySql.rowCount(); Returns how affected rows ; Use this if want to know why nothing is working (Can be used anywhere after $MySql.Startup()) $MySql.debug(); Returns nothing ; Retrives the last MysqlError set $MySql.SQLerror(); Returns error (If any) Here is some example code:
      #include <miniSQL\miniSQL.au3> ; Set default dir for our dlls (Only has to be done once) _miniSQL_setDllDir(@ScriptDir & "\miniSQL") ; Declared as CONST since we never want to accidentally change the variables original value Local Const $MySql = _miniSQL_LoadLibrary() ;Connect to database & Init library If Not $MySql.Startup("localhost", "user", "pass", "db", 3306) Then MsgBox(0, "Failed to start library", $MySql.debug()) Exit EndIf With $MySql .prepare("SELECT * FROM members") If Not .execute() Then MsgBox(0, "Failed to execute query", .sqlError()) Local $oRows = .fetchAll() ; Print how many rows got affected by latest query ConsoleWrite(StringFormat("Number of rows to display: %s", .rowCount()) & @CRLF) ; we use isObj to check if we got any result. If IsObj($oRows) Then For $row In $oRows ConsoleWrite(StringFormat("Id: %s", $row.id) & @CRLF) ConsoleWrite(StringFormat("Name: %s", $row.name) & @CRLF) ConsoleWrite(StringFormat("Bio: %s", $row.bio) & @CRLF) Next Else ConsoleWrite("No rows to show"&@CRLF) EndIf EndWith ; Use this in your app when you are done using the database $MySql.Shutdown() #include <miniSQL\miniSQL.au3> ; Set default dir for our dlls (Only has to be done once) _miniSQL_setDllDir(@ScriptDir & "\miniSQL") ; Declared as CONST since we never want to accidentally change the variables original value Local Const $MySql = _miniSQL_LoadLibrary() ;Connect to database & Init library If Not $MySql.Startup("localhost", "user", "pass", "db", 3306) Then MsgBox(0, "Failed to start library", $MySql.debug()) Exit EndIf With $MySql ; We use an array to make our query look nicer Local $vars = [":name", @UserName&Random(1,10,1)] ; Prepare our statement .prepare("UPDATE members SET name = :name WHERE 1") If Not .execute($vars) Then MsgBox(0, "Failed to execute query", .sqlError()) ; Print how many rows got affected by latest query ConsoleWrite(StringFormat("Example 1 rows affected: %s", .rowCount()) & @CRLF) EndWith ; We can also prepare like this With $MySql Local $vars = ["?", @UserName, "?", 1] ; Prepare our statement .prepare("UPDATE members SET name = ? WHERE id = ?") If Not .execute($vars) Then MsgBox(0, "Failed to execute query", .sqlError()) ; Print how many rows got affected by latest query ConsoleWrite(StringFormat("Example 2 rows affected: %s", .rowCount()) & @CRLF) EndWith ; Use this in your app when you are done using the database $MySql.Shutdown()  
      With $MySql ; We use an array to make our query look nicer Local $vars = ["?", 1] ;Line by line prepared statement .prepareClean(); .prepareGlue("SELECT *") .prepareGlue("FROM members") .prepareGlue("WHERE id = ?") If Not .execute($vars) Then MsgBox(0, "Failed to execute query", .sqlError()) ; Print how many rows got affected by latest query ConsoleWrite(StringFormat("Example 1 rows affected: %s", .rowCount()) & @CRLF) EndWith ; Use this in your app when you are done using the database $MySql.Shutdown() Some code from one of my applications at work using this UDF
      With $MySql .prepareClean() .prepareGlue("SELECT") .prepareGlue("cases.cases_dedu_casenumber,") .prepareGlue("cases.cases_created_by_ugid,") .prepareGlue("cases.cases_dedu_ftg,") .prepareGlue("cases.cases_date_created,") .prepareGlue("cases.cases_date_finished,") .prepareGlue("cases.cases_protocol_director,") .prepareGlue("cases.cases_finished_by_ugid,") .prepareGlue("IFNULL(uid1.names_name, 'none') as createdByFullname,") .prepareGlue("IFNULL(uid2.names_name, 'none') as finishedByFullname") .prepareGlue("FROM cases") .prepareGlue("LEFT JOIN names AS uid1") .prepareGlue("ON cases.cases_created_by_ugid = uid1.names_uid") .prepareGlue("LEFT JOIN names AS uid2") .prepareGlue("ON cases.cases_finished_by_ugid = uid2.names_uid") if $_App_Case_SearchFor Then .prepareGlue(StringFormat("WHERE cases_dedu_casenumber LIKE '%s'",$_App_Case_SearchFor)) .prepareGlue("ORDER BY cases.cases_date_created DESC") .prepareGlue("LIMIT 0, 30") if not .execute() then return __ThrowException(.sqlError()) Local $oRows = .fetchAll() EndWith  
       
      Git: https://gitlab.com/xdtarrexd/MiniSQL.git
      Download: Zip generated from Github
       
      Feel free to open your mind about this