Martin_Martin Posted April 12, 2022 Share Posted April 12, 2022 (edited) Hello, I am beginner in this and I am trying to create an .exe file, which I can call with my Powershell script. This file is supposed to read query in database, select it and automatically export into .csv file or at least .txt file. Problem is, that it is not working for me. Can someone help me ? With MessageBox it is working (but I can not do it with MSGbox because this script must work in Point of sale terminal on real stations and customer can not see this), but I really do not know how FileWrite works. Here is the code: Any help will be appretiated. Thank you very much #include <GUIConstantsEx.au3> #include <ButtonConstants.au3> #include <WinAPI.au3> #include <WindowsConstants.au3> #include <GuiStatusBar.au3> #include <Array.au3> #include <File.au3> #include <Constants.au3> #include <Logging.au3> #include <WinAPIFiles.au3> Global $Select = "select * from storeandforward where rownum < 8 order by creationtime desc ;", $conn Global $RecordSet, $Data $conn = ObjCreate( "ADODB.Connection" ) $DSN = "DSN=" & "DB" & ";" & "Uid=db2" & ";" & "Pwd=" & "db2" $conn.Open($DSN) $rs = ObjCreate( "ADODB.RecordSet" ) If @error Then Return "Failed to create Object; (""ADODB.Connection"")" EndIf $RecordSet = $conn.Execute($Select) $Data = $RecordSet.GetRows #_ArrayDisplay($Data) $conn.close Edited April 20, 2022 by Martin_Martin Link to comment Share on other sites More sharing options...
Danyfirex Posted April 12, 2022 Share Posted April 12, 2022 You can use _FileWriteFromArray Saludos Danysys.com AutoIt... UDFs: VirusTotal API 2.0 UDF - libZPlay UDF - Apps: Guitar Tab Tester - VirusTotal Hash Checker Examples: Text-to-Speech ISpVoice Interface - Get installed applications - Enable/Disable Network connection PrintHookProc - WINTRUST - Mute Microphone Level - Get Connected NetWorks - Create NetWork Connection ShortCut Link to comment Share on other sites More sharing options...
mLipok Posted April 12, 2022 Share Posted April 12, 2022 I would like to recomend you to use * ADO.au3 UDF * btw 2️⃣4️⃣um Danyfirex 1 Signature beginning:* Please remember: "AutoIt"..... * Wondering who uses AutoIt and what it can be used for ? * Forum Rules ** ADO.au3 UDF * POP3.au3 UDF * XML.au3 UDF * IE on Windows 11 * How to ask ChatGPT for AutoIt Code * for other useful stuff click the following button: Spoiler Any of my own code posted anywhere on the forum is available for use by others without any restriction of any kind. My contribution (my own projects): * Debenu Quick PDF Library - UDF * Debenu PDF Viewer SDK - UDF * Acrobat Reader - ActiveX Viewer * UDF for PDFCreator v1.x.x * XZip - UDF * AppCompatFlags UDF * CrowdinAPI UDF * _WinMergeCompare2Files() * _JavaExceptionAdd() * _IsBeta() * Writing DPI Awareness App - workaround * _AutoIt_RequiredVersion() * Chilkatsoft.au3 UDF * TeamViewer.au3 UDF * JavaManagement UDF * VIES over SOAP * WinSCP UDF * GHAPI UDF - modest begining - comunication with GitHub REST API * ErrorLog.au3 UDF - A logging Library * Include Dependency Tree (Tool for analyzing script relations) * Show_Macro_Values.au3 * My contribution to others projects or UDF based on others projects: * _sql.au3 UDF * POP3.au3 UDF * RTF Printer - UDF * XML.au3 UDF * ADO.au3 UDF * SMTP Mailer UDF * Dual Monitor resolution detection * * 2GUI on Dual Monitor System * _SciLexer.au3 UDF * SciTE - Lexer for console pane * Useful links: * Forum Rules * Forum etiquette * Forum Information and FAQs * How to post code on the forum * AutoIt Online Documentation * AutoIt Online Beta Documentation * SciTE4AutoIt3 getting started * Convert text blocks to AutoIt code * Games made in Autoit * Programming related sites * Polish AutoIt Tutorial * DllCall Code Generator * Wiki: * Expand your knowledge - AutoIt Wiki * Collection of User Defined Functions * How to use HelpFile * Good coding practices in AutoIt * OpenOffice/LibreOffice/XLS Related: WriterDemo.au3 * XLS/MDB from scratch with ADOX IE Related: * How to use IE.au3 UDF with AutoIt v3.3.14.x * Why isn't Autoit able to click a Javascript Dialog? * Clicking javascript button with no ID * IE document >> save as MHT file * IETab Switcher (by LarsJ ) * HTML Entities * _IEquerySelectorAll() (by uncommon) * IE in TaskScheduler * IE Embedded Control Versioning (use IE9+ and HTML5 in a GUI) * PDF Related: * How to get reference to PDF object embeded in IE * IE on Windows 11 * I encourage you to read: * Global Vars * Best Coding Practices * Please explain code used in Help file for several File functions * OOP-like approach in AutoIt * UDF-Spec Questions * EXAMPLE: How To Catch ConsoleWrite() output to a file or to CMD *I also encourage you to check awesome @trancexx code: * Create COM objects from modules without any demand on user to register anything. * Another COM object registering stuff * OnHungApp handler * Avoid "AutoIt Error" message box in unknown errors * HTML editor * winhttp.au3 related : * https://www.autoitscript.com/forum/topic/206771-winhttpau3-download-problem-youre-speaking-plain-http-to-an-ssl-enabled-server-port/ "Homo sum; humani nil a me alienum puto" - Publius Terentius Afer"Program are meant to be read by humans and only incidentally for computers and execute" - Donald Knuth, "The Art of Computer Programming" , be and \\//_. Anticipating Errors : "Any program that accepts data from a user must include code to validate that data before sending it to the data store. You cannot rely on the data store, ...., or even your programming language to notify you of problems. You must check every byte entered by your users, making sure that data is the correct type for its field and that required fields are not empty." Signature last update: 2023-04-24 Link to comment Share on other sites More sharing options...
jchd Posted April 12, 2022 Share Posted April 12, 2022 (edited) You can easily export the result of any SELECT statement in many formats, among them csv. Say you create an SQLite database named Example.sq3 with a table Sample defined thusly CREATE TABLE Sample (Key CHAR, Value INT); Say you load it with some data:INSERT INTO Sample VALUES ('a',1), ('c',3), ('b',2), ('z',26), ('y',25), ('x',24); You can dump the table Sample in .CSV format using this, for instance: Local $sstr ; actually dummy here _SQLite_SQLiteExe("Example.sq3", _ ".mode csv" & @CRLF & _ ".headers on" & @CRLF & _ ".output sample.csv" & @CRLF & _ "select * from Sample order by key;" & @CRLF & _ ".quit", $sStr) ; Check the result created ConsoleWrite(FileRead("sample.csv")) You can use any complicated SELECT you need. Familiarize yourself with all the flexibility offered by the CLI (sqlite3.exe). Using the latest version from sqlite.org will bring you most. BTW the .mode command lets you choose a number of output formats: sqlite> .help mode .mode MODE ?OPTIONS? Set output mode MODE is one of: ascii Columns/rows delimited by 0x1F and 0x1E box Tables using unicode box-drawing characters csv Comma-separated values column Output in columns. (See .width) html HTML <table> code insert SQL insert statements for TABLE json Results in a JSON array line One value per line list Values delimited by "|" markdown Markdown table format qbox Shorthand for "box --width 60 --quote" quote Escape answers as for SQL table ASCII-art table tabs Tab-separated values tcl TCL list elements OPTIONS: (for columnar modes or insert mode): --wrap N Wrap output lines to no longer than N characters --wordwrap B Wrap or not at word boundaries per B (on/off) --ww Shorthand for "--wordwrap 1" --quote Quote output text as SQL literals --noquote Do not quote output text TABLE The name of SQL table used for "insert" mode Edited April 12, 2022 by jchd 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 hereRegExp tutorial: enough to get startedPCRE 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 More sharing options...
Martin_Martin Posted April 19, 2022 Author Share Posted April 19, 2022 On 4/12/2022 at 3:06 PM, mLipok said: I would like to recomend you to use * ADO.au3 UDF * btw 2️⃣4️⃣um Yeah, thank you for your help, but as I mentioned I am beginner, so I have no idea what am I seeing in this script Link to comment Share on other sites More sharing options...
Martin_Martin Posted April 19, 2022 Author Share Posted April 19, 2022 On 4/12/2022 at 3:07 PM, jchd said: You can easily export the result of any SELECT statement in many formats, among them csv. Say you create an SQLite database named Example.sq3 with a table Sample defined thusly CREATE TABLE Sample (Key CHAR, Value INT); Say you load it with some data:INSERT INTO Sample VALUES ('a',1), ('c',3), ('b',2), ('z',26), ('y',25), ('x',24); You can dump the table Sample in .CSV format using this, for instance: Local $sstr ; actually dummy here _SQLite_SQLiteExe("Example.sq3", _ ".mode csv" & @CRLF & _ ".headers on" & @CRLF & _ ".output sample.csv" & @CRLF & _ "select * from Sample order by key;" & @CRLF & _ ".quit", $sStr) ; Check the result created ConsoleWrite(FileRead("sample.csv")) You can use any complicated SELECT you need. Familiarize yourself with all the flexibility offered by the CLI (sqlite3.exe). Using the latest version from sqlite.org will bring you most. BTW the .mode command lets you choose a number of output formats: sqlite> .help mode .mode MODE ?OPTIONS? Set output mode MODE is one of: ascii Columns/rows delimited by 0x1F and 0x1E box Tables using unicode box-drawing characters csv Comma-separated values column Output in columns. (See .width) html HTML <table> code insert SQL insert statements for TABLE json Results in a JSON array line One value per line list Values delimited by "|" markdown Markdown table format qbox Shorthand for "box --width 60 --quote" quote Escape answers as for SQL table ASCII-art table tabs Tab-separated values tcl TCL list elements OPTIONS: (for columnar modes or insert mode): --wrap N Wrap output lines to no longer than N characters --wordwrap B Wrap or not at word boundaries per B (on/off) --ww Shorthand for "--wordwrap 1" --quote Quote output text as SQL literals --noquote Do not quote output text TABLE The name of SQL table used for "insert" mode I am using ODBC Management studio for SQL script and thats it, because on every station, that is live, there is only this app and I can not change that, so I do not know how can I use SQL lite in this case, or am I missing something ? Link to comment Share on other sites More sharing options...
jchd Posted April 19, 2022 Share Posted April 19, 2022 I wrote my answer assuming the DB engine in use was SQLite, since you include the relevant UDFs in your code. So remove those unneeded includes and tell us which DB engine you use: MySQL, MSSQL, SQL Server, Postgres, DB2, ... ODBC and ADO are just engine-agnostic wrappers to interface the actual DB engine. Every DB engine has its own facilities (or not) to import, export, backup, restore data. 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 hereRegExp tutorial: enough to get startedPCRE 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 More sharing options...
Martin_Martin Posted April 20, 2022 Author Share Posted April 20, 2022 20 hours ago, jchd said: I wrote my answer assuming the DB engine in use was SQLite, since you include the relevant UDFs in your code. So remove those unneeded includes and tell us which DB engine you use: MySQL, MSSQL, SQL Server, Postgres, DB2, ... ODBC and ADO are just engine-agnostic wrappers to interface the actual DB engine. Every DB engine has its own facilities (or not) to import, export, backup, restore data. Yeah sorry, I did not include that. There is Oracle's MySQL Link to comment Share on other sites More sharing options...
Martin_Martin Posted April 20, 2022 Author Share Posted April 20, 2022 On 4/12/2022 at 2:49 PM, Danyfirex said: You can use _FileWriteFromArray Saludos Yes, but I found out, that I can use this only for 1D arrays. Link to comment Share on other sites More sharing options...
jchd Posted April 20, 2022 Share Posted April 20, 2022 https://www.google.com/search?client=firefox-b-d&q=mysql+export+to+csv returns a full load of answers. 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 hereRegExp tutorial: enough to get startedPCRE 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 More sharing options...
Martin_Martin Posted May 2, 2022 Author Share Posted May 2, 2022 (edited) On 4/19/2022 at 11:47 AM, jchd said: I wrote my answer assuming the DB engine in use was SQLite, since you include the relevant UDFs in your code. So remove those unneeded includes and tell us which DB engine you use: MySQL, MSSQL, SQL Server, Postgres, DB2, ... ODBC and ADO are just engine-agnostic wrappers to interface the actual DB engine. Every DB engine has its own facilities (or not) to import, export, backup, restore data. So this is my script, that is returning result into .csv file, but problem is, that I am not getting titles of columns now and I do not know why. Do you know where can be the issue ? Thank you very much in advance #include <GUIConstantsEx.au3> #include <ButtonConstants.au3> #include <WinAPI.au3> #include <WindowsConstants.au3> #include <GuiStatusBar.au3> #include <SQLite.au3> #include <SQLite.dll.au3> #include <Array.au3> #include <File.au3> #include <Constants.au3> #include <Logging.au3> #include <WinAPIFiles.au3> ;; Variable for Logging definition Global $HideGUI=0 Global $Dbg=2 ; Dbg Level definieren, wenn über Commando Zeile nichts übergeben wurde, dann ist Default 2 -> Logfile schreiben ;$typetext="fail" == 1 ;$typetext="question" == 2 ;$typetext="warning" == 3 ;$typetext="info" == 4 Global $RecordSet Global $Data Global $Data1 ; Location of csv file Global $sDataFilePath = "C:\Service\EssoMpay\DBExport.csv" ;; Function(s) start script_logging($Dbg, "Test import from db to file: <<<<<<<<<<<<<<<<<<< Start >>>>>>>>>>>>>>>>>>>", 4, $HideGUI) GetDbRows(); ExportDataToCsv($Data); Func GetDbRows() Local $SQL_Query = "select * from storeandforward where rownum < 8 order by creationtime desc;" $connection = ObjCreate( "ADODB.Connection" ) $result = ObjCreate("ADODB.RecordSet") $DSN = "DSN=" & "DB" & ";" & "Uid=db2" & ";" & "Pwd=" & "db2" $connection.Open($DSN) $result.Open($SQL_Query, $connection) $Data = $result.GetRows() EndFunc Func ExportDataToCsv(const $array) If Not FileExists($sDataFilePath) Then FileWriteLine($sDataFilePath, "Result") EndIf For $i = 0 to UBound($array, 1) - 1 $k = $i + 1 FileWriteLine($sDataFilePath, "Rownum: " & $k) For $j = 0 to UBound($array, 2) - 1 FileWriteLine($sDataFilePath, $array[$i][$j]) Next FileWriteLine($sDataFilePath, " ") Next EndFunc Edited May 2, 2022 by Martin_Martin Link to comment Share on other sites More sharing options...
jchd Posted May 2, 2022 Share Posted May 2, 2022 Remove the SQLite #includes since you don't use this engine. Try this: expandcollapse popup#include <GUIConstantsEx.au3> #include <ButtonConstants.au3> #include <WinAPI.au3> #include <WindowsConstants.au3> #include <GuiStatusBar.au3> #include <Array.au3> #include <File.au3> #include <Constants.au3> #include <Logging.au3> #include <WinAPIFiles.au3> ;; Variable for Logging definition Global $HideGUI=0 Global $Dbg=2 ; Dbg Level definieren, wenn über Commando Zeile nichts übergeben wurde, dann ist Default 2 -> Logfile schreiben ;$typetext="fail" == 1 ;$typetext="question" == 2 ;$typetext="warning" == 3 ;$typetext="info" == 4 Global $oConnection Global $aData Global $aNames ; Location of csv file Global $sDataFilePath = "C:\Service\EssoMpay\DBExport.csv" ;; Function(s) start script_logging($Dbg, "Test import from db to file: <<<<<<<<<<<<<<<<<<< Start >>>>>>>>>>>>>>>>>>>", 4, $HideGUI) DbStartup() GetDbRows() DbShutdown() ExportDataToCsv(); Func DbStartup() $oConnection = ObjCreate( "ADODB.Connection" ) Local $sDSN = "DSN=" & "DB" & ";" & "Uid=db2" & ";" & "Pwd=" & "db2" $oConnection.Open($sDSN) EndFunc Func DbShutdown() $oConnection.Close() EndFunc Func DbGetRows() Local $sSQL_Query = "select * from storeandforward where rownum < 8 order by creationtime desc;" Local $oResult = ObjCreate("ADODB.RecordSet") $oResult.Open($sSQL_Query, $oConnection) $aData = $oResult.GetRows() ; load array $aData with rows $aNames[UBound($aData, 2)] ; array to hold column names For $i = 0 To UBound($aNames) - 1 $aNames[$i] = $oResult.Fields($i).Name Next EndFunc Func ExportDataToCsv() ;~ If Not FileExists($sDataFilePath) Then ;~ FileWriteLine($sDataFilePath, "Result") ; ??? should be column names! ;~ EndIf Local $s = _ArrayToString($aNames, ",") & @CRLF ; column names $s &= _ArrayToString($aData, ",") FileWriteLine($sDataFilePath, $s) ; data rows ;~ For $i = 0 to UBound($array, 1) - 1 ;~ $k = $i + 1 ; ;~ FileWriteLine($sDataFilePath, "Rownum: " & $k) ;~ For $j = 0 to UBound($array, 2) - 1 ;~ FileWriteLine($sDataFilePath, $array[$i][$j]) ;~ Next ;~ FileWriteLine($sDataFilePath, " ") ;~ Next EndFunc 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 hereRegExp tutorial: enough to get startedPCRE 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 More sharing options...
junkew Posted May 3, 2022 Share Posted May 3, 2022 Why would you make an exe in AutoIt to call from Powershell where you directly can create the adodb connection within powershell? FAQ 31 How to click some elements, FAQ 40 Test automation with AutoIt, Multithreading CLR .NET Powershell CMDLets Link to comment Share on other sites More sharing options...
Skysnake Posted May 7, 2022 Share Posted May 7, 2022 Hi Just to get clarity What _exactly_ do you wish to do? Is the problem the DB connection, the data or the CSV output? How much you need the user to interact? I have a complex setup where AutoIt ADO queries DB Places result in ListView for user to see On button grabs listview content and Writes to CSV Which part of your process do you need help with? Skynake Skysnake Why is the snake in the sky? Link to comment Share on other sites More sharing options...
Recommended Posts
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 accountSign in
Already have an account? Sign in here.
Sign In Now