Jump to content

How to get or read a single data in SQLite database?


Recommended Posts

If I have SQLite database table containing Product List and Product Price, how can I get or read a single product price from that database?

For example, look image below

What command should I use?

Can anyone please give me a little clue or guide?

I still don't have any code for this. I only have code to insert value to SQLite database based on my question yesterday.

Thank You

Ilustration SQLitedb.png

Edited by HezzelQuartz
Link to comment
Share on other sites

18 minutes ago, argumentum said:

Let's see. You've been here since 2019. The help files gives clear SQL examples for your question. The pic. is not a Win32 GUI. Wassup ?, what are you up to ?

Could you please give me the name of the function in help file so that I can read by myself?

Link to comment
Share on other sites

1 hour ago, HezzelQuartz said:

Could you please give me the name of the function in help file so that I can read by myself?

a little clue :

$query = "SELECT Price FROM tablename WHERE Product = 'Book B';"

 

Musashi-C64.png

"In the beginning the Universe was created. This has made a lot of people very angry and been widely regarded as a bad move."

Link to comment
Share on other sites

Posting the very same request on the SQLite mailing list won't help you with AutoIt.

Run this :

; #include <Array.au3>
#include <SQLite.au3>

_SQLite_Startup(@ScriptDir & "\" & "sqlite3.dll", False, 1)
If @error Then
    MsgBox(16, "SQLite Error", "SQLite3.dll Can't be Loaded!")
    Exit -1
EndIf

Local $sDatabase = @ScriptDir & "\" & "MyBooks.db"      ; adjust filename
Local $hDatabase = _SQLite_Open($sDatabase)

Local $row
_SQLite_QuerySingleRow($hDatabase, "select price from books where product = 'Book B';", $row)
MsgBox(0, "Price of Book B", $row[1])

_SQLite_Close($hDatabase)
_SQLite_Shutdown()

And make yourself a favor: open and use AutoIt help.

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)

Link to comment
Share on other sites

On 8/30/2024 at 1:56 PM, jchd said:

Posting the very same request on the SQLite mailing list won't help you with AutoIt.

Run this :

; #include <Array.au3>
#include <SQLite.au3>

_SQLite_Startup(@ScriptDir & "\" & "sqlite3.dll", False, 1)
If @error Then
    MsgBox(16, "SQLite Error", "SQLite3.dll Can't be Loaded!")
    Exit -1
EndIf

Local $sDatabase = @ScriptDir & "\" & "MyBooks.db"      ; adjust filename
Local $hDatabase = _SQLite_Open($sDatabase)

Local $row
_SQLite_QuerySingleRow($hDatabase, "select price from books where product = 'Book B';", $row)
MsgBox(0, "Price of Book B", $row[1])

_SQLite_Close($hDatabase)
_SQLite_Shutdown()

And make yourself a favor: open and use AutoIt help.

If I have SQLite database table containing Category, Product List, and Product Price (image below),
how can I get or read a the latest product from a category from that database?

For example, I want to search my latest entry from book category so that the result become "Book E"?

I mean like this

I think if I execute this command below,
"select product from books where category = 'Book'

the result will be:
Book A
Book B
Book C
Book D
Book E

In this case, I don't know the book name and how many kind of book I have in this category
I just want to get the latest book I Input, so that the result will be "Book E"
But in this case, I don't know the book name is "Book E"

I just want the latest result from this command:
"select product from books where category = 'Book'

What SQLite command or AutoIt Function or both of them should I use to get the latest entry from that category?

Sorry If my explanation is confusing

Book.png

Edited by HezzelQuartz
Link to comment
Share on other sites

  

I think I got the answer:

SELECT Product FROM Product_List WHERE No = (SELECT max(no) FROM Product_List where category = "Book")

then I tried to

DELETE FROM Product_List WHERE No = (SELECT max(no) FROM Product_List Where Category = "Book")

Then "No" Column become
1
2
3
4
6
7
8
9
10

How to keep "No" sorted like this below?
1
2
3
4
5
6
7
8
9

Thank You

Link to comment
Share on other sites

The SQL language is based on set theory. If you define a set of RGB colors for instance, that means {'Red', 'Green', 'Blue'} but this set has no inherent ordering. {'Blue', 'Red', 'Green'} is the exact same set. One can sometimes define an ordering on a set but this is NOT a property of the set. So in SQL, "first" and "last" row in a table (= a set) mean nothing.

Hopefully in SQL you can use the ORDER BY clause to explicitely define an ordering for the resultset of a query. For instance, you can use:
SELECT Product FROM Product_List WHERE category = 'Book' order by no desc limit 1;
(note: 'Book' and not "Book")

Your "No" column contains an identifier, which is NOT a row sequence number. Think of an identifier as a EAN or UPC barcode label which you can't read by yourself: it uniquely identifies an item but means nothing per se.

You should take an SQL primer somewhere on the web.

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)

Link to comment
Share on other sites

46 minutes ago, jchd said:

The SQL language is based on set theory. If you define a set of RGB colors for instance, that means {'Red', 'Green', 'Blue'} but this set has no inherent ordering. {'Blue', 'Red', 'Green'} is the exact same set. One can sometimes define an ordering on a set but this is NOT a property of the set. So in SQL, "first" and "last" row in a table (= a set) mean nothing.

Hopefully in SQL you can use the ORDER BY clause to explicitely define an ordering for the resultset of a query. For instance, you can use:
SELECT Product FROM Product_List WHERE category = 'Book' order by no desc limit 1;
(note: 'Book' and not "Book")

Your "No" column contains an identifier, which is NOT a row sequence number. Think of an identifier as a EAN or UPC barcode label which you can't read by yourself: it uniquely identifies an item but means nothing per se.

You should take an SQL primer somewhere on the web.

So we cannot use numbering as row sequence number?
Is there any alternative for numbering every row?

What if there is no column "no" in the table?
how to delete latest entry if "no" column is not available there?

Do you have recommended web to learn?
w3schools.com?
tutorialspoint?

Link to comment
Share on other sites

What if there is no column "no" in the table? Then i do not think you can determine latest input from what i see. The fist column ("no" in your case) is identifier ('unique id') that is auto increasing if after adding next record to table. While you can have sum of inputs, and if there is more than one with identical requested in returned data from query, you can not determine witch of returned records is last inserted and you can not determine whom to remove if no ID is present.

I dont think order in DB is guaranteed but i can be wrong. SQL does not guarantee it from what i can read as for mysql

Quote

MySQL by default seems to order by the record structure on disk, (which can include out-of-sequence entries due to deletions and optimisations) but it often initially fools developers into not bother using order-by clauses because the data appears to default to primary-key ordering, which is not the case!

Quote

SQLite will never provide any guarantees for what order rows are stored into, nor how they are selected into (w/o an order by clause), whether you insert them with values() or not.

 

Edited by bogQ

TCP server and client - Learning about TCP servers and clients connection
Au3 oIrrlicht - Irrlicht project
Au3impact - Another 3D DLL game engine for autoit. (3impact 3Drad related)



460px-Thief-4-temp-banner.jpg
There are those that believe that the perfect heist lies in the preparation.
Some say that it’s all in the timing, seizing the right opportunity. Others even say it’s the ability to leave no trace behind, be a ghost.

 
Link to comment
Share on other sites

17 minutes ago, bogQ said:

What if there is no column "no" in the table? Then i do not think you can determine latest input from what i see. The fist column ("no" in your case) is identifier ('unique id') that is auto increasing if after adding next record to table. While you can have sum of inputs, and if there is more than one with identical requested in returned data from query, you can not determine witch of returned records is last inserted and you can not determine whom to remove if no ID is present.

I dont think order in DB is guaranteed but i can be wrong. SQL does not guarantee it from what i can read as for mysql

 

So we cannot use numbering as row sequence number?
Is there any alternative for numbering every row?

Link to comment
Share on other sites

As previously said a set (= SQL table) doesn't have an inherent order, even less a sequence number. Think of an SQL table as an opaque plastic bag containing all your items. Shake the bag. There is no order in the bag, but you can ask SQL to exhibit selected/all items and display them in the order you find useful, but YOU have to explicitely request the ordering method.

In this context, "last entered" row doesn't make any sense. If you insist on keeping a note of the entry sequence, add a new column to store an entry/last modify timestamp.

Row numbering is "for your eyes" given a specific query. And you CAN indeed show row sequence number in the resultset of a query by using SQL window functions.

Say you create a table:

CREATE TABLE t (id integer primary key, a char, b char);
INSERT INTO t (a, b) VALUES('a', 'one'),
                     ('b', 'four'),
                     ('a', 'two'),
                     ('c', 'five'),
                     ('d', 'ten'),
                     ('a', 'three'),
                     ('c', 'six');

Query the table (output has NO order!):
select * from t;

id    a    b
1    a    one
2    b    four
3    a    two
4    c    five
5    d    ten
6    a    three
7    c    six

Remove a row:
delete from t where b = 'ten'
select * from t;

id    a    b
1    a    one
2    b    four
3    a    two
4    c    five
6    a    three
7    c    six

Show row numbers of a query, ordered by b descending:
SELECT
       row_number() OVER win AS row_number,
       id,
       a,
       b
FROM t
WINDOW win AS (ORDER BY b desc);

row_number    id    a    b
1                         3    a    two
2                         6    a    three
3                         7    c    six
4                         1    a    one
5                         2    b    four
6                         4    c    five

Show row numbers of a query, ordered by id ascending:
SELECT
       row_number() OVER win AS row_number,
       id,
       a,
       b
FROM t
WINDOW win AS (ORDER BY id);

row_number    id    a    b
1                          1    a    one
2                          2    b    four
3                          3    a    two
4                          4    c    five
5                          6    a    three
6                          7    c    six

 

Once again, row sequence numbers are not part of any table and are useless in 99.9999% of use cases.

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)

Link to comment
Share on other sites

Index (indices) are of no use here and are something completely different.

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)

Link to comment
Share on other sites

On 9/2/2024 at 1:27 PM, jchd said:

index (indices) are of no use here and are something completely different.

agree
more is a link with a tutorial and I chose this link because it starts with what is rowid (unfortunate choice, it's a good tutorial anyway)

 

One way to have serial numbering without holes is to rebuild the array.
as long as you don't really care about the ID being changed, and it's not related to any other table.
here I continue the example of jchd

; https://www.autoitscript.com/forum/topic/212227-how-to-get-or-read-a-single-data-in-sqlite-database/?do=findComment&comment=1536547

#include <SQLite.au3>

_SQLite_Startup(@ScriptDir & "\sqlite3\sqlite3.dll", False, 1)
If @error Then ConsoleWrite("! SQLite3.dll Can't be Loaded!" & @CRLF)

Local $db = _SQLite_Open()
If @error Then ConsoleWrite("! Open database failed" & @CRLF)

Local $SQL = "CREATE TABLE t (id integer primary key, a char, b char);"
SQLite_Query($db, $SQL)

$SQL = "INSERT INTO t (a, b) VALUES('a', 'one'), ('b', 'four'), ('a', 'two'), ('c', 'five'), ('d', 'ten'), ('a', 'three'), ('c', 'six');"
SQLite_Query($db, $SQL)
_Show("SELECT * FROM t")

$SQL = "delete from t where b = 'ten'"
SQLite_Query($db, $SQL)
_Show("SELECT * FROM t")

$SQL = "SELECT row_number() OVER win AS row_number, id, a, b FROM t WINDOW win AS (ORDER BY b desc);"
_Show($SQL)

$SQL = "SELECT row_number() OVER win AS row_number, id, a, b FROM t WINDOW win AS (ORDER BY id);"
_Show($SQL)

$SQL = "CREATE TEMPORARY TABLE temp_table as SELECT ROW_NUMBER() OVER (ORDER BY id) AS new_id, a, b FROM t;"
SQLite_Query($db, $SQL)
$SQL = "DELETE FROM t;"
SQLite_Query($db, $SQL)
$SQL = "INSERT INTO t (id, a, b) SELECT new_id, a, b FROM temp_table;"
SQLite_Query($db, $SQL)

_Show("SELECT * FROM t")

$SQL = "DROP TABLE temp_table;"
SQLite_Query($db, $SQL)

_SQLite_Close($db)
;--------------------------------------------------------------------------------------------------------------------------------
Func _Show($SQL, $Line = @ScriptLineNumber)
    Local $aResult = SQLite_Query($db, $SQL)
    If $aResult = Null Then
        ConsoleWrite("(" & $Line & ") " & "Query failed" & @CRLF)
    Else
        ConsoleWrite("(" & $Line & ") ~~~~~~~~~~~~~~~~~~" & @CRLF)
        _SQLite_Display2DResult($aResult)
        ConsoleWrite("" & @CRLF)

    EndIf
EndFunc   ;==>_Show
;--------------------------------------------------------------------------------------------------------------------------------
Func SQLite_Query($hDB, $sQuery)
    Local $aResult, $iRows, $iColumns
    _SQLite_GetTable2D($hDB, $sQuery, $aResult, $iRows, $iColumns)
    If @error Then
        Return SetError(1, 0, False)
    Else
        Return SetError(0, UBound($aResult, 1) - 1, $aResult)
    EndIf
EndFunc   ;==>SQLite_Query

 

 

Edited by ioa747
correction _Show()

I know that I know nothing

Link to comment
Share on other sites

Another way to use integer sequential id to mimic row sequence is to use a trigger on insert and one on delete with a recursive cte to adjust the ids as wanted, but that's ugly and useless.

 

Again row sequence numbers are jus "for your eyes only" and carry zero information. From the table posted by OP in post #6, run

select * from Product_List WHERE = 'Pen';

You get ids (= No) from 6 and up, not row sequence numbers. Use the row_number() window function for that.

It's exactly like line numbers shown by some text editors: they are metadata, NOT part of the text, void of any semantic. Yet early Basic mandated unique (non sequential) numbers at the head of code lines, with the resulting spaghetti code we all remember (goto 4753).

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)

Link to comment
Share on other sites

@jchd@ioa747
Thank You

I have another question, how to insert date and time into sql table?
Is it as simple as below?

insert into Book (Category, Product, Price, Date, Time) Values ('Book', 'Book E', '18000', '04/09/2024', '13:10')

Or should follow some format?
------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Next question is, if there is no "no" or rowid table for sorting,
Can I short based on date and time?
Please look my example below

Thank You

NewBook.png

Link to comment
Share on other sites

#include <SQLite.au3>

_SQLite_Startup(@ScriptDir & "\sqlite3\sqlite3.dll", False, 1)
If @error Then ConsoleWrite("! SQLite3.dll Can't be Loaded!" & @CRLF)

Local $db = _SQLite_Open()
If @error Then ConsoleWrite("! Open database failed" & @CRLF)

Local $SQL = "CREATE TABLE Book (Category TEXT, Product TEXT, Price INTEGER, Date DATETIME);"
SQLite_Query($db, $SQL)
Local $aQuery

$SQL = "insert into Book (Category, Product, Price, Date) Values"
$SQL &= "('Book', 'Book D', '18000', datetime('now', '+3 hours')),"
$SQL &= "('Book', 'Book G', '21000', '2024-09-06 15:30:00'),"
$SQL &= "('Book', 'Book F', '11000', '2024-09-06 15:10:00'),"
$SQL &= "('Book', 'Book E', '15000', '2024-09-05 13:10:00');"

SQLite_Query($db, $SQL)

$SQL = "SELECT * FROM Book;"
_Show($SQL)

$SQL = "SELECT Category, Product, Price, Date FROM Book ORDER BY Date;"
_Show($SQL)

$SQL = "SELECT ROW_NUMBER() OVER (ORDER BY Date) AS No, Category, Product, Price, Date FROM Book ORDER BY Date;"
_Show($SQL)

$SQL = "SELECT ROW_NUMBER() OVER (ORDER BY Date) AS No, Category, Product, Price, DATE(Date) AS Date, TIME(Date) AS Time FROM Book ORDER BY Date;"
_Show($SQL)

_SQLite_Close($db)

;--------------------------------------------------------------------------------------------------------------------------------
Func _Show($SQL, $Line = @ScriptLineNumber)
    Local $aResult = SQLite_Query($db, $SQL)
    If $aResult = Null Then
        ConsoleWrite("(" & $Line & ") " & "Query failed" & @CRLF)
    Else
        ConsoleWrite("(" & $Line & ") ~~~~~~~~~~~~~~~~~~" & @CRLF)
        _SQLite_Display2DResult($aResult)
        ConsoleWrite("" & @CRLF)

    EndIf
EndFunc   ;==>_Show
;--------------------------------------------------------------------------------------------------------------------------------
Func SQLite_Query($hDB, $sQuery)
    Local $aResult, $iRows, $iColumns
    _SQLite_GetTable2D($hDB, $sQuery, $aResult, $iRows, $iColumns)
    If @error Then
        Return SetError(1, 0, False)
    Else
        Return SetError(0, UBound($aResult, 1) - 1, $aResult)
    EndIf
EndFunc   ;==>SQLite_Query

 

https://www.sqlite.org/lang_datefunc.html

Edit:
"INSERT INTO Book (Category, Product, Price, Date) VALUES ('Book', 'Book E', '15000', datetime('now'));"
datetime('now')) returns the current time in UTC.

If your local time is different, you’ll need to adjust for your timezone.

For example, if your local time is 3 hours ahead of UTC, you can adjust the time like this:
"INSERT INTO Book (Category, Product, Price, Date) VALUES ('Book', 'Book E', '15000', datetime('now', '+3 hours'));"

 

Edited by ioa747
Update

I know that I know nothing

Link to comment
Share on other sites

1 hour ago, Andreik said:

Why would you save date and time in two different columns?

Just trying several possibilites and learning
-----------------------------------------------------------------------------------------------------------------
I tried to sort by date, time, and exact_time in my table below using this code.

Select Product FROM Book ORDER BY Exact_Time ASC


Sorting result is correct by using exact_time.
If I used date (format: dd/mm/yyyy), the sorting result is wrong

Should I use yyyy/mm/dd to sort the date?
Cannot use dd/mm/yyyy?

Newest Book.png

Link to comment
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
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...