Jump to content
Sign in to follow this  
Centrally

SQL query question

Recommended Posts

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

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

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

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

 

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

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

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  

  • Recently Browsing   0 members

    No registered users viewing this page.

  • Similar Content

    • By mLipok
      I want to present BETA Version of my ADO.au3 UDF.
      This is modifed version of _sql.au3 UDF.
       
      For that I want to thanks : ; Chris Lambert, eltorro, Elias Assad Neto, CarlH
       
      This is first public release , and still is as BETA
       
       
      DOWNLOAD LINK (in download section): 
       
       
      Have fun,
      mLipok
       
       
      EDIT: 2016-06-03
      Below some interesting topics about databases:
       
       
      EDIT 2016/07/04:
      For more info about ADO look here:
      https://www.autoitscript.com/wiki/ADO
      FOR EXAMPLE DATABASE use AdventureWorksDW2016_EXT.bak from:
      https://github.com/microsoft/sql-server-samples/releases/download/adventureworks/AdventureWorksDW2016_EXT.bak
      I will relay on this database in my examples.
       
    • By shino54
      Hello,
      I would like a query to know if an entry exists
      Thank you in advance.
      $sQuery = "SELECT Alger FROM garage where auto='BL1879'" $result1 = $result.Fields("Alger").Value if $result1="" Then MsgBox(0, "ERROR", "BAD not exist") Else MsgBox(0, "Success!", "OK exist") EndIf Exit  
    • By Nas
      Hi everyone,
      I am trying to make a script that runs a query and show it to me to see if everything is right and then decide if I finish it or not so I made a little script as below :
      #include <ADO.au3> #include <Array.au3> #include <MsgBoxConstants.au3> #include <AutoItConstants.au3> _ADO_EVENTS_SetUp(True) _ADO_ComErrorHandler_UserFunction(_ADO_COMErrorHandler) Local $sDriver = 'SQL Server' Local $sDatabase = 'DataBase' ; change this string to YourDatabaseName Local $sServer = 'Localhost' ; change this string to YourServerLocation Local $sConnectionString = 'DRIVER={' & $sDriver & '};SERVER=' & $sServer & ';DATABASE=' & $sDatabase & ';UID=' & ';PWD=' & ';' ;~ Global $Query = _ ;~ "BEGIN TRAN" & @CRLF & _ ;~ "UPDATE Table" & @CRLF & _ ;~ "SET HOUR = 4" & @CRLF & _ ;~ "WHERE CUST = 'TEST'" & @CRLF & _ ;~ "SELECT * FROM Table" & @CRLF & _ ;~ "WHERE CUST = 'TEST'" & @CRLF & _ ;~ "ROLLBACK TRAN" Global $Query = _ "BEGIN TRAN" & @CRLF & _ "SELECT * FROM Table" & @CRLF & _ "WHERE CUST = 'TEST'" & @CRLF & _ "ROLLBACK TRAN" _Query_Display($sConnectionString, $Query) Func _Query_Display($sConnectionString, $sQUERY) ; Create connection object Local $oConnection = _ADO_Connection_Create() ; Open connection with $sConnectionString _ADO_Connection_OpenConString($oConnection, $sConnectionString) If @error Then Return SetError(@error, @extended, $ADO_RET_FAILURE) ; Executing some query directly to Array of Arrays (instead to $oRecordset) Local $aRecordset = _ADO_Execute($oConnection, $sQUERY, True) ; Clean Up _ADO_Connection_Close($oConnection) $oConnection = Null ; Display Array Content with column names as headers _ADO_Recordset_Display($aRecordset, 'Query Result') EndFunc ;==> _Query_Display When I ran this script it works great, but when I run the query below :
      Global $Query = _ "BEGIN TRAN" & @CRLF & _ "UPDATE Table" & @CRLF & _ "SET HOUR = 4" & @CRLF & _ "WHERE CUST = 'TEST'" & @CRLF & _ "SELECT * FROM Table" & @CRLF & _ "WHERE CUST = 'TEST'" & @CRLF & _ "ROLLBACK TRAN" It doesn't show anything, when I take those begin and rollback it does what it should but still not showing me anything at all, is there a way around it that you know of?
      Thank you.
    • By Nas
      Hello Guys,
       
      I am running the Ado example script, if I run this line, it runs without errors :
      Local $sConnectionString = 'DRIVER={' & $sDriver & '};SERVER=' & $sServer & ';DATABASE=' & $sDatabase & ';UID=' & $sUser & ';PWD=' & $sPassword & ';' But when I try the windows auth one , it failed everytime :
      Func _Example_MSSQL_WindowsAuthorization() Local $sDatabase = 'AdventureWorks2016' Local $sServer = 'SQLSRV' _Example_5_MSSQL_WinAuth($sServer, $sDatabase, "Select * from Person.Address") EndFunc here is the error :
       
      ADO.au3 v.2.1.16 BETA (1204) : ==> COM Error intercepted !
      $oADO_Error.description is:     Provider cannot be found. It may not be properly installed.
      $oADO_Error.windescription:     Exception occurred.
      $oADO_Error.number is:     80020009
      $oADO_Error.lastdllerror is:     0
      $oADO_Error.scriptline is:     1204
      $oADO_Error.source is:     ADODB.Connection
      $oADO_Error.helpfile is:     C:\Windows\HELP\ADO270.CHM
      $oADO_Error.helpcontext is:     1240655
      By the way, I have 64x windows server 2016 with SQL Server , I already installed the odbc my sql connector, any thought on this will be greatly appreciate it.
    • 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 ).
×
×
  • Create New...