Jump to content
Sign in to follow this  
Centrally

SQL query question

Recommended Posts

Centrally

I'm trying to use autoIT script to populate database but I bumped on one problem.

What I need is query that would check if value in specific field exist (like serial name of product), if it exist than update selected fields or if not insert new value.

This is initial query I have made:

"INSERT INTO `Baza1` (`Datum Objave`,`Serija`,`Ime predmeta`,`Broj pregleda`,`cijena`,`Link do oglasa`,`Koeficijent` ) VALUES (" & $datum1 & "," & $serija & ", " & $ime1 & ", " & $pregledBroj1 & ", " & $cijena1 & ", " & $pathlink & ", " & $koeficient & ")"

This query would only insert new data without checking if it already exist.

I have tried to use replace query but I simply cannot understand it's format.

I don't know how to select what field to check for duplicate and how to update other fields if criteria is matched.

Any explanation or brief part of code example is highly appreciated. Thanks

 

Share this post


Link to post
Share on other sites
MHz

REPLACE is an alias for INSERT for compatibility with other databases so I would not be concerned about using it.

This is how to use UPDATE to change the values.

Here is an example using the SQLite3.exe.

Create a table

CREATE TABLE "tab" VALUES ('col1', 'col2');

Insert values

INSERT INTO "tab" VALUES ('cat', 'dog');

Show output using select

SELECT * FROM "tab";
cat|dog

Update if "col1" = 'pig'. (pig does not exist in col1 so value in col2 is not set)

UPDATE "tab" SET "col2" = 'mouse' WHERE "col1" = 'pig';

Show output using select (no change)

SELECT * FROM "tab";
cat|dog

Update if "col1" = 'cat'

UPDATE "tab" SET "col2" = 'mouse' WHERE "col1" = 'cat';

Show output using select (changed)

SELECT * FROM "tab";
cat|mouse

This is probably a slow method as you are using UPDATE no matter if needs updating or not. You could use SELECT to get the column of interest with all of the values. Find in the values which exist that you have, and then UPDATE the values that are missing which is probably what Zedna is doing with his nested SELECT. Although if you knew the value did not exist in the column when using SELECT, then you could just use INSERT for the new row. :)

UPDATE with comments

UPDATE "tab" -- update this table
SET "col2" = 'dog' -- set value dog in this column
WHERE "col1" = 'cat' --only where cat is in this column
;

Share this post


Link to post
Share on other sites
Centrally

Thank you for your answers I will respond back to this topic when I test your examples.

Share this post


Link to post
Share on other sites
Xenobiologist

Using a "real" database like DB2 then the command Merge is what you are looking for.

(null)


Scripts & functions Organize Includes Let Scite organize the include files

Yahtzee The game "Yahtzee" (Kniffel, DiceLion)

LoginWrapper Secure scripts by adding a query (authentication)

_RunOnlyOnThis UDF Make sure that a script can only be executed on ... (Windows / HD / ...)

Internet-Café Server/Client Application Open CD, Start Browser, Lock remote client, etc.

MultipleFuncsWithOneHotkey Start different funcs by hitting one hotkey different times

Share this post


Link to post
Share on other sites
jchd

BTW I suspect you use MySQL. While schema names (tables, columns, ...) may be enclosed in backquotes, literal strings should use single quotes and even then, should be escaped (have significant single quotes doubled).

Your question is perhaps more a DB design question.

BTW, there is no such thing as a "real" DB engine, just like for programmers.


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
Centrally

 

REPLACE is an alias for INSERT for compatibility with other databases so I would not be concerned about using it.

This is how to use UPDATE to change the values.

Here is an example using the SQLite3.exe.

Create a table

CREATE TABLE "tab" VALUES ('col1', 'col2');

Insert values

INSERT INTO "tab" VALUES ('cat', 'dog');

Show output using select

SELECT * FROM "tab";
cat|dog

Update if "col1" = 'pig'. (pig does not exist in col1 so value in col2 is not set)

UPDATE "tab" SET "col2" = 'mouse' WHERE "col1" = 'pig';

Show output using select (no change)

SELECT * FROM "tab";
cat|dog

Update if "col1" = 'cat'

UPDATE "tab" SET "col2" = 'mouse' WHERE "col1" = 'cat';

Show output using select (changed)

SELECT * FROM "tab";
cat|mouse

This is probably a slow method as you are using UPDATE no matter if needs updating or not. You could use SELECT to get the column of interest with all of the values. Find in the values which exist that you have, and then UPDATE the values that are missing which is probably what Zedna is doing with his nested SELECT. Although if you knew the value did not exist in the column when using SELECT, then you could just use INSERT for the new row. :)

UPDATE with comments

UPDATE "tab" -- update this table
SET "col2" = 'dog' -- set value dog in this column
WHERE "col1" = 'cat' --only where cat is in this column
;

 

First off all I am using MySQL and UDF >EzMySql

Now from your set of examples I have learned how to check if specific value in one field exist but I still don't know how to do next thing.

So if I use 

UPDATE "tab" SET "col2" = 'mouse' WHERE "col1" = 'pig';

It does check table for pig and if found is set to mouse, but now if it wasn't found how to add it in a new row. Something like ELSE statement is what I'm looking for 

that would add new row if existing value is not found.

@Zedna

I don't understand this part of query:

WHERE NOT EXISTS(SELECT 1 FROM table WHERE id = your_id)

What this 1 stand for and what id/your_id should be placed here. 

@jchd

I don't care about SQLi yet because this part of db should be manually uploaded to display website with charts few times a day, meaning no actual interaction with website itself.

EDIT:

What do you think about this approach?

INSERT INTO table1
  (`col1`, `col2`, `col3`, `col4`)
VALUES
  ('val1', 'val2', 'val3', 'val4')
ON DUPLICATE KEY UPDATE
  `col2`='val2',
  `col3`='val3', [...]
Edited by Centrally

Share this post


Link to post
Share on other sites
Centrally

UPDATE:

This is my end working query if someone is on same road in future:

"INSERT INTO `baza1` (`Datum Objave`,`Serija`,`Ime predmeta`,`Broj pregleda`,`cijena`,`Link do oglasa`,`Koeficijent`) VALUES (" & $datum1 & "," & $serija & ", " & $ime1 & ", " & $pregledBroj1 & ", " & $cijena1 & ", " & $pathlink & ", " & $koeficient & ") ON DUPLICATE KEY UPDATE  `Broj pregleda`=" & $pregledBroj1 & ",  `cijena`=" & $cijena1 & ", `Koeficijent`=" & $koeficient & ""

I removed primary key and set unique ones to id and `Ime predmeta` which is checked for duplicate and decided upon for either updating or inserting.

I would like to give big thanks for all of you here trying to help me find solution.

Share this post


Link to post
Share on other sites
MHz

The id column mentioned is a custom column that many seem to use to show the row number. In SQLite. this is created regardless and can be accessed as rowid, _rowid_ or oid. I cannot speak for all databases. I may consider they do something similar perhaps.

To access the rowid in SQLite is similar to

SELECT "rowid", * FROM "table";

which would output the rowid and the rest of the columns.
So you do not need to create the custom column id though someone may correct me based on better knowledge. Creating a integer primary key can be an alias for the rowid so the rowid is shown to you as say the custom column id.

@Centrally

If that statement solves your initial problem then you have done well. ;)

I am not MySQL tested nor heavily experienced with databases yet. :)

Edited by MHz

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  

  • Similar Content

    • dangr82
      By dangr82
       
      I have created this function for a database, but I can not make it work. I always have two error messages: "not an error" ... and the file created, in the script directory, does not contain anything.
      Global $sDBName = "Hen.db" Func DatabaseTable() Local $sConnDB _SQLite_Startup() If @error Then MsgBox($MB_SYSTEMMODAL, "SQLite Error", "SQLite.dll Can't be Loaded!") Exit -1 EndIf $sConnDB = _SQLite_Open($sDBName) If @error Then MsgBox($MB_SYSTEMMODAL, "SQLite Error", "Can't Load Database!") Exit -1 EndIf If Not _SQLite_Exec($sDBName, 'CREATE TABLE Animal ("Name", "Age");') = $SQLITE_OK Then MsgBox($MB_SYSTEMMODAL, "SQLite Error", _SQLite_ErrMsg()) If Not _SQLite_Exec($sDBName, 'INSERT INTO Animale VALUES ("Charlie","5");') = $SQLITE_OK Then MsgBox($MB_SYSTEMMODAL, "SQLite Error", _SQLite_ErrMsg()) _SQLite_Close($sConnDB) _SQLite_Shutdown() EndFunc  
    • argumentum
      By argumentum
      ..let's say I store in a mysql column "[1,2,11,12,123]".
      How can I make s query to get all those rows that is 1, or is 12, etc ?
      I'm using  mysqlnd 5.0.11-dev - 20120503 
      Any advise on what technique I should use is welcomed
      Thanks
      PS: ..I'm adding a comma to each end, as in  [,1,2,11,12,123,] and will search with like %,12,% .
      Not pretty but I'm in a hurry and can't come up with a better solution =/
    • sc4ry
      By sc4ry
      Dear all,
      I already have a formula which will select doublicates, but sometimes there might be entries with additional information starting after "-", which I now want to trim away.
      Current formula is:
      Select DISTINCT a.title, a.oid, a.size, a.disk from DB a, DB b where (a.title like b.title and a.oid <> b.oid)" & $ActiveDisks_Filter & " AND (a.comment <> 'Delete' AND b.comment <> 'Delete') Order by a.title ASC, a.size DESC; testwise I want to add a simple solution like left, but afterwards I get an error but I do not know why.
      Select DISTINCT a.title, a.oid, a.size, a.disk from DB a, DB b where (left(a.title,15) like b.title and a.oid <> b.oid) Order by a.title ASC, a.size DESC; Error: near "(": syntax error: Finally I would like to insert intstr to search for "-" but currently I am not able to extend my current code =/
      Thanks a lot for your help.
      EDIT: hey, I managed it, left was not working also it was somehow shown that the tool knowed the comment. I did it now with substr+instr
      (substr(a.title, 1, instr(a.title, ' - '))  
    • AndyS19
      By AndyS19
      I have code that does a WMI SQL query to find all defined printers, and I want to parse the returned object in several places.  However, after parsing it the first time, all other times fail to find any printer objects.
      Here is my test code:
      test() Func test() Local $oPrinters, $oPrinter, $err, $cnt, $oP, $query $query = "SELECT * FROM Win32_Printer" $oPrinters = doQuery($query) $err = @error LogMsg("+++: $err = " & $err & ", isObj($oPrinters) = " & IsObj($oPrinters)) If ($err == 0) Then LogMsg("FIRST LOOP") ; <=== FIRST LOOP $cnt = 0 $oP = $oPrinters LogMsg("+++: isObj($oP) = " & IsObj($oP)) For $oPrinter In $oP $cnt += 1 LogMsg("+++: isObj($oPrinter): " & IsObj($oPrinter) & ", $oPrinter.Name ==>" & $oPrinter.Name & "<==") Next LogMsg("+++: Found " & $cnt & " printers") LogMsg("SECOND LOOP") ; <== SECOND LOOP $cnt = 0 $oP = $oPrinters LogMsg("+++: isObj($oP) = " & IsObj($oP)) For $oPrinter In $oP $cnt += 1 LogMsg("+++: isObj($oPrinter): " & IsObj($oPrinter) & ", $oPrinter.Name ==>" & $oPrinter.Name & "<==") Next LogMsg("+++: Found " & $cnt & " printers") EndIf EndFunc ;==>test Func doQuery($sQuery, $lnum = @ScriptLineNumber) #forceref $lnum LogMsg("+++:" & $lnum & ": doQuery(" & '"' & $sQuery & '"' & ") entered") Local $oWMIService, $oResults, $errstr Local $wbemFlags = BitOR(0x20, 0x10) ; $wbemFlagReturnImmediately and wbemFlagForwardOnly $oWMIService = ObjGet("winmgmts:\\" & "localhost" & "\root\CIMV2") If (IsObj($oWMIService)) Then $oResults = $oWMIService.ExecQuery($sQuery, "WQL", $wbemFlags) If (IsObj($oResults)) Then LogMsg("+++: doQuery() returns @error = 0, Good: returning the object") Return (SetError(0, 0, $oResults)) ;;; Good: return the object Else $errstr = "" _ & "WMI Query failed." & @CRLF _ & "This is the query:" & @CRLF _ & " " & $sQuery LogMsg("+++: ====>" & $errstr & "<===") LogMsg("+++: doQuery() returns @error = 1") Return (SetError(1, 0, $errstr)) ; Error: Query faled EndIf Else $errstr = "" _ & "WMI Output" & @CRLF _ & "No WMI Objects Found for class: " & @CRLF _ & "Win32_PrinterDriver" & @CRLF _ & "using this query:" & @CRLF _ & " " & $sQuery LogMsg("+++: ====>" & $errstr & "<===") MsgBox(0, "ERROR", $errstr) ; Error: Cannot get $oWMIService object Exit (1) EndIf EndFunc ;==>doQuery Func LogMsg($msg, $lnum = @ScriptLineNumber) ConsoleWrite("+++:" & $lnum & ": " & $msg & @CRLF) EndFunc ;==>LogMsg Parsing the returned $oPrinters object shows 5 printers:
      +++:15: FIRST LOOP +++:18: +++: isObj($oP) = 1 +++:22: +++: isObj($oPrinter): 1, $oPrinter.Name ==>Microsoft XPS Document Writer<== +++:22: +++: isObj($oPrinter): 1, $oPrinter.Name ==>Microsoft Office Document Image Writer<== +++:22: +++: isObj($oPrinter): 1, $oPrinter.Name ==>Fax<== +++:22: +++: isObj($oPrinter): 1, $oPrinter.Name ==>Canon MG7100 series Printer WS<== +++:22: +++: isObj($oPrinter): 1, $oPrinter.Name ==>Canon MG6100 series Printer WS<== +++:24: +++: Found 5 printers Parsing it again, shows no printers:
      +++:26: SECOND LOOP +++:29: +++: isObj($oP) = 1 +++:35: +++: Found 0 printers  
    • GhostLine
      By GhostLine
      Hello guys !
      I'm stuck in something stupid (I guess), but since I've no clue on how to solve it, here I come
      I'm trying to collect the result of the query "select @@hostname" on MSSQL Server, but it doesn't work ... and I'm sure I'm connected to the database (I've successfully seen the database treeview). 

      #Region ;**** Directives created by AutoIt3Wrapper_GUI **** #AutoIt3Wrapper_UseX64=n #EndRegion ;**** Directives created by AutoIt3Wrapper_GUI **** #include<_sql.au3> #include<array.au3> Local $aData,$iRows,$iColumns ;Server ID and credentials for tCards Global $ServerAddressT = "10.200.88.1" Global $ServerUserNameT = "user" Global $ServerPasswordT = "password" Global $DatabaseNameT = "DataBASE" ;Connect to DB _SQL_RegisterErrorHandler();register the error handler to prevent hard crash on COM error $OADODB = _SQL_Startup() If $OADODB = $SQL_ERROR Then MsgBox(0 + 16 + 262144, "Error", _SQL_GetErrMsg()) If _sql_Connect(-1, $ServerAddressT, $DatabaseNameT, $ServerUserNameT, $ServerPasswordT) = $SQL_ERROR Then     MsgBox(0 + 16 + 262144, "Error 1", _SQL_GetErrMsg())     _SQL_Close()     Exit Else     If _SQL_Execute(-1,"select @@SERVERNAME") = $SQL_ERROR then         Msgbox(0 + 16 +262144,"Error",_SQL_GetErrMsg())     Else         _ArrayDisplay(_SQL_GetTable(-1,"select @@SERVERNAME",$aData,$iRows,$iColumns)) ;~         $toto = _SQL_Execute(-1,"select @@SERVERNAME") ;~         _ArrayDisplay($toto)     EndIf EndIf
×