Jump to content

Recommended Posts

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

 

 

Share this post


Link to post
Share on other sites

Interesting coding approach.

 

EDIT:
Added here:
https://www.autoitscript.com/wiki/User_Defined_Functions#Databases_and_web_connections

 

Edited by mLipok

Signature beginning:   Wondering who uses AutoIT and what it can be used for ?
* GHAPI UDF - modest beginning - communication with GitHub REST API Forum Rules *
ADO.au3 UDF     POP3.au3 UDF     XML.au3 UDF    How to use IE.au3  UDF with  AutoIt v3.3.14.x  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 APIErrorLog.au3 UDF - A logging Library *

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 * 

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

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 *

"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"
:naughty:  :ranting:, 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: 2019-10-01

Share this post


Link to post
Share on other sites

I beg to strongly differ.

While this may seem simple to use for SQL newbies, I doubt you can create "serious" SQL queries this way, I mean in real-world applications. Simple queries don't need any of these glue functions and routine non-trivial queries become an horrible mess almost impossible to understand.

Further, it tends to teach newcomers an extremely limited grammar/dialect, instead of exposing the full power of SQL. In my book I call this totally counter-productive and utterly deceptive in the long run.

For instance, imagining you have all Laravel wrapped as AutoIt functions, how would the following (still simple and pretty readable) query translate?

create table T(date integer,test char);
insert into T
values (1,'clim'),(3,'clim'),(7,'amb'),(10,'amb'),(12,'xxx'),
(13,'clim'),(15,'clim'),(20,'clim'),(22,'amb'),(25,'amb');

select
    min(date) as fromdate,
    max(date) as enddate,
    test
from (--get closest preceeding different key
    select
        t.*,
        max(t2.date) as key2
    from
        t
        left join
        t t2
    on t2.date < t.date and t2.test != t.test
    group by t.date
)
group by key2

Nom think of 4 or 8 complex subqueries on 7-table joins...

Laziness never pays long term!


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

@mLipok  thx

@jchd Thank you for your feedback and forgive me my google Translater english, but I am a different opinion.

On 2.3.2017 at 10:25 AM, jchd said:

While this may seem simple to use for SQL newbies, I doubt you can create "serious" SQL queries this way, I mean in real-world applications. 

 

What are the reputable SQL query and what are simplistic? In my real applications, more than 90% of all SQL queries are rather simple.

On 2.3.2017 at 10:25 AM, jchd said:

Simple queries don't need any of these glue functions and routine non-trivial queries become an horrible mess almost impossible to understand.

I do not think so. I find the laravel prinizip much more clearly and for my SQL queries it is sufficient.

On 2.3.2017 at 10:25 AM, jchd said:

Further, it tends to teach newcomers an extremely limited grammar/dialect, instead of exposing the full power of SQL. In my book I call this totally counter-productive and utterly deceptive in the long run.

For instance, imagining you have all Laravel wrapped as AutoIt functions, how would the following (still simple and pretty readable) query translate?

I agree with you. Newcomers should first learn sql before using these udf. This is similar to Javascript frameworks. But why can not I make life easier if I can sql already.

For subquery I have so far no solution, so you would have to actually execute a $ SQL_raw ('..').

Share this post


Link to post
Share on other sites

You're telling me that it is simpler and clearer to write something like

$Sentence.Myself.Subject()
$Sentence.Verb("to be").Present.Person(1)
$Sentence.Negation.Absolute()
$Sentence.Verb("to convince").Participle.Past()
$Sentence.FinalPoint()
ConsoleWrite(SentenceBuild($Sentence) & @LF)

rather than

ConsoleWrite("I am not convinced." & @LF)

That may fit your mood or models but I dare to insist that this is counter-productive.

A non-trivial application can be a typical simple invoicing system, for instance. There you're likely to find a table of clients, a table of delivery locations, a table of invoicing addresses, a table of orders/invoices, a table of items, a table of items ordered (some delivered and some still pending delivery), a table of paiements associated to orders and invoices, and most probably some more tables to fit the real world (suppliers, stock management, ...)

I don't buy the idea that such a common application can use 90% of flat queries.


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

  • Similar Content

    • By argumentum
      #include <SQLite.au3> ;-- When SQLite is compiled with the JSON1 extensions it provides builtin tools ;-- for manipulating JSON data stored in the database. ;-- This is a gist showing SQLite return query as a JSON object. ;-- https://www.sqlite.org/json1.html Example() Func Example() _SQLite_Startup() ; "<your path>\sqlite3.dll", False, 1) ; https://www.autoitscript.com/autoit3/docs/libfunctions/_SQLite_Startup.htm _SQLite_Open() ; ...if you can not run this due to errors, get the latest DLL from https://www.sqlite.org/ If _SQLite_Exec(-1, "CREATE TABLE users (id INTEGER PRIMARY KEY NOT NULL, full_name TEXT NOT NULL, email TEXT NOT NULL, created DATE NOT NULL );") Then Return 4 If _SQLite_Exec(-1, 'INSERT INTO users VALUES ' & _ '(1, "Bob McFett", "bmcfett@hunters.com", "32-01-01"),' & _ '(2, "Angus O''Vader","angus.o@destroyers.com", "02-03-04"),' & _ '(3, "Imperator Colin", "c@c.c", "01-01-01");') Then Return 5 ; -- Get query data as a JSON object using the ; -- json_group_object() [1] and json_object() [2] functions. _SQLite_GetTable2d_ArrayToConsole("SELECT" & _ " json_group_object(" & _ " email," & _ " json_object('full_name', full_name, 'created', created)" & _ " ) AS json_result" & _ " FROM (SELECT * FROM users WHERE created > ""02-01-01"");") ; {"bmcfett@hunters.com":{"full_name":"Bob McFett","created":"32-01-01"},"angus.o@destroyers.com":{"full_name":"Angus O'Vader","created":"02-03-04"}} ; -- Get query data as a JSON object using the ; -- json_group_array() function to maintain order. _SQLite_GetTable2d_ArrayToConsole("SELECT" & _ " json_group_array(" & _ " json_object('full_name', full_name, 'created', created)" & _ " ) AS my_json_result_OrAnythingReally" & _ " FROM (SELECT * FROM users ORDER BY created);") ; [{"full_name":"Imperator Colin","created":"01-01-01"},{"full_name":"Angus O'Vader","created":"02-03-04"},{"full_name":"Bob McFett","created":"32-01-01"}] ;-- Links ;-- [1] https://www.sqlite.org/json1.html#jgroupobject ;-- [2] https://www.sqlite.org/json1.html#jobj ; example found at https://gist.github.com/akehrer/481a38477dd0518ec0086ac66e38e0e2 EndFunc ;==>Example Func _SQLite_GetTable2d_ArrayToConsole($sSQL, $hDB = -1) Local $aResult, $iRows, $iColumns If _SQLite_GetTable2d($hDB, $sSQL, $aResult, $iRows, $iColumns) Then ConsoleWrite("! SQLite Error: " & _SQLite_ErrCode($hDB) & @CRLF & "! " & _SQLite_ErrMsg($hDB) & @CRLF) Else _SQLite_Display2DResult($aResult) EndIf ConsoleWrite(@CRLF) EndFunc ;==>_SQLite_GetTable2d_ArrayToConsole Based on this example, you can build your own query. 
      The code has all the explanations.
      Enjoy  
    • By argumentum
      #include <SQLite.au3> ;~ #include <SQLite.dll.au3> Local $hQuery, $aRow, $aNames _SQLite_Startup() ConsoleWrite("_SQLite_LibVersion=" & _SQLite_LibVersion() & @CRLF) _SQLite_Open() ; open :memory: Database _SQLite_Exec(-1, "CREATE TABLE aTest (A,B int not null unique ,C text);") _SQLite_Exec(-1, "INSERT INTO aTest(a,b,c) VALUES ('c','2','World');") _SQLite_Exec(-1, "INSERT INTO aTest(a,b,c) VALUES ('b','3',' ');") _SQLite_Exec(-1, "INSERT INTO aTest(a,b,c) VALUES ('a','1','Hello');") _SQLite_Query(-1, "SELECT _ROWID_,* FROM aTest ORDER BY a;", $hQuery) _SQLite_FetchTypes($hQuery, $aNames) ; Read out Column Types ConsoleWrite(StringFormat(" %-10s %-10s %-10s %-10s ", $aNames[0], $aNames[1], $aNames[2], $aNames[3]) & @CRLF) _SQLite_FetchNames($hQuery, $aNames) ; Read out Column Names ConsoleWrite(StringFormat(" %-10s %-10s %-10s %-10s ", $aNames[0], $aNames[1], $aNames[2], $aNames[3]) & @CRLF) While _SQLite_FetchData($hQuery, $aRow) = $SQLITE_OK ConsoleWrite(StringFormat(" %-10s %-10s %-10s %-10s ", $aRow[0], $aRow[1], $aRow[2], $aRow[3]) & @CRLF) WEnd _SQLite_Exec(-1, "DROP TABLE aTest;") _SQLite_Close() _SQLite_Shutdown() ; Output: ; INTEGER int text ; rowid A B C ; 3 a 1 Hello ; 2 b 3 ; 1 c 2 World Func _SQLite_FetchTypes($hQuery, ByRef $aTypes) Dim $aTypes[1] If __SQLite_hChk($hQuery, 3, False) Then Return SetError(@error, 0, $SQLITE_MISUSE) Local $avDataCnt = DllCall($__g_hDll_SQLite, "int:cdecl", "sqlite3_column_count", "ptr", $hQuery) If @error Then Return SetError(1, @error, $SQLITE_MISUSE) ; DllCall error If $avDataCnt[0] <= 0 Then Return SetError(-1, 0, $SQLITE_DONE) ReDim $aTypes[$avDataCnt[0]] Local $avColName For $iCnt = 0 To $avDataCnt[0] - 1 $avColName = DllCall($__g_hDll_SQLite, "wstr:cdecl", "sqlite3_column_decltype16", "ptr", $hQuery, "int", $iCnt) If @error Then Return SetError(2, @error, $SQLITE_MISUSE) ; DllCall error $aTypes[$iCnt] = $avColName[0] Next Return $SQLITE_OK EndFunc ;==>_SQLite_FetchTypes  If you wanna build a proper JSON string, you may want to know if is {"int":123} or {"text":"123"}
      and for that, this can help, obviously only when declared in the SQLite table.
    • By argumentum
      $sQueryUpdateTime = "select intUpdateTime from tblStudies " . $where . " ORDER BY intUpdateTime DESC limit 1"; $rs = mysqli_query($conn, $sQueryUpdateTime); $row = mysqli_fetch_assoc($rs); the above used to take 300+ ms. to query. Then I set it as index and takes 30 ms. Cool.
      $sQuery = "select * from tblStudies " . $where . " ORDER BY StudyDate DESC limit $offset,$rows"; // takes 30 ms. on the indexed int $sQuery = "select * from tblStudies " . $where . " ORDER BY StudyDate DESC , PatientName ASC limit $offset,$rows"; // takes 300 ms. due to "PatientName" been a text field, even as I did index it So my observation is that "PatientName" takes a long time to sort, even tho "$rows = 20". Sorting text in 20 rows should be fast.
      ..tho, I find that any 2nd argument in the ORDER BY is just slow.
      Is there a way to query this in a way to have a faster result back ?
      Thanks
      PS: added ADD INDEX `StudyDate_2` (`StudyDate`, `PatientBirthDate`) USING BTREE;  and searched by those two with not much speed change ( StudyDate and PatientBirthDate are integer ).
    • By argumentum
      I was thinking but I don't have the experience, so you may have the experience.
      I was thinking to chop a DB with 100.000 ( 20 columns ) in 10.000 DB chunks ( 10 DBs ) and query concurrently all of them to speed up a search, then add the results. Is that a sound idea ? Or will I run in trouble down the road. Should a DB better be keep in one piece ?
      The DB is now in MySQL. I wanna do all this chopping and use SQLite. 
      Thanks
      [solved]
×
×
  • Create New...