JDBC - SQLITE Select to variable - sqlite

I am trying to run a query / select statement and save it in a variable. I know how to get something specific from a specific column but not from counting rows.
This is working as I getting MYID specifically.
ResultSet MYIDrs = stmtCFG.executeQuery( "SELECT rowid, MYID from MYINDEX order by rowid desc limit 1;" );
MYID = MYIDrs.getString("MYID");
Now I am trying to count the rows that works in SQLite client but not in the jdbc as I can't figure out what to request.
this is what I have but is not resulting in what I am expecting.
ResultSet FILE_COUNTrs = stmtCFG.executeQuery( "SELECT count(*) from TABLE where MYID = '"+MYID+"';");
FILE_COUNT = FILE_COUNTrs.getString(?????);
problem or question is: What do I put in the ????? as I already tried everything.
I am expecting to see a number.

I am really sorry I found what I was looking for by assigning a name TOTAL
This is my code and it works...
ResultSet FILE_COUNTrs = stmtCFG.executeQuery( "SELECT count(*) AS TOTAL from TABLE where MYID = '"+MYID+"';");
FILE_COUNT = FILE_COUNTrs.getString("TOTAL");

You use wrong data type. COUNT(*) returns Integer type, Not String.
You can do like this without assigning a label for COUNT(*)
int FILE_COUNT = FILE_COUNTrs.getInt(1); // 1: is the column index of COUNT(*)

Related

SQLite: count number of records in multiple tables

Using SQLite I can get all tablenames in my database:
SELECT name AS Tablename FROM sqlite_master WHERE type = 'table'
Result will be some tablenames, for example:
Tablename:
cars
planes
bus
How could I have a SQL query that will count the number of records for each table that is found, result should be:
Tablename Records:
cars 100
planes 200
bus 300
I understand that in this example I simply could run 3 SELECT COUNT() statements, however the number of tables can vary so that I can not hardcode a fixed number of SELECT COUNT()
All table and column names in a statement need to be known at the time it is compiled, so you can't do this dynamically.
You'd have to programmatically build up a new query string based on the results of getting the table names from sqlite_master. Either one query per table like you mentioned, or all together by creating something that looks like
SELECT 'table1' AS Tablename, count(*) AS Records FROM table1
UNION ALL
SELECT 'table2', count(*) FROM table2
-- etc.
You don't mention what language you're working in, so in psuedo-code of a functional style:
var allcounts = query("SELECT name FROM sqlite_master WHERE type = 'table'")
.map(name -> "SELECT '$name' AS Tablename, count(*) AS Records FROM \"$name\"")
.join(" UNION ALL ");
var totals = query(allcounts);

Can I use CASE WHEN outside of SELECT in SQLite/Conditional Structure in SQLite?

In SQL Server, I can use IF conditional structure to execute some statements if a condition is true. According to this and this, there seem to be no such structure in SQLite.
I want to check if a table exist, if it does, do nothing, if not, do a lot of things including creating tables, inserting and deleting data from other tables and updating as well:
CASE WHEN ((SELECT COUNT(*) FROM sqlite_master WHERE type = 'table' AND name = 'TraitsSwap') = 1) THEN
-- 50 lines of code, including CREATE, DROP, INSERT, DELETE and UPDATE statements, with random() in used
ELSE
-- Do nothing
END
Is there anyway I can achieve this? The code includes usage of random() and it requires consistent result (i.e, only random in the first time). I am sorry if this sounds unreasonable, but this is in context of game modding, so I cannot really change the backend code to run separated transaction code.
I think there may be an alternative if there is a function in SQLite that can execute a string/statement block and return a result. For that, I can transform the query into
SELECT CASE WHEN ((SELECT COUNT(*) FROM sqlite_master WHERE type = 'table' AND name = 'TraitsSwap') = 1) THEN
ExecuteCode("Code; RETURN 1;")
ELSE
0
END
I tried
SELECT CASE WHEN ((SELECT COUNT(*) FROM sqlite_master WHERE type = 'table' AND name = 'TraitsSwap') = 1) THEN
SELECT 1;
INSERT INTO Foo(Test) VALUES("");
SELECT "A";
ELSE
SELECT 1;
SELECT 2;
SELECT "A";
END
but it's unsuccessful, the error is
near "SELECT": syntax error: SELECT CASE WHEN ((SELECT COUNT(*) FROM
sqlite_master WHERE type = 'table' AND name = 'TraitsSwap') = 1) THEN
SELECT

how to return something else when nothing is found?

My current query:
select timestamp from messagesTable
where partner_jid='" + lastUserJid + "' AND msg='.roll'
order by timestamp DESC LIMIT 1 OFFSET 1;
This works fine... unless the values don't exist in the database.
If values do not exist in database, then it should Select * messagesTable; or do nothing if possible.
Is there a way to add a check for that within the same query? It has to be the same query unfortunately because I need to execute things through adb shell. I've been trying things out with CASE but I do not really understand much about SQL.
You can just append a second query, with a WHERE filter that checks whether the first query did not return anything:
SELECT *
FROM (SELECT timestamp
FROM messagesTable
WHERE partner_jid = ?
AND msg = '.roll'
ORDER BY timestamp DESC
LIMIT 1 OFFSET 1)
UNION ALL
SELECT -1 -- or "timestamp FROM msgTab", or whatever
WHERE NOT EXISTS (SELECT timestamp
FROM messagesTable
WHERE partner_jid = ?
AND msg = '.roll');

Sqlite select default rows if not exists

Sorry to pester with a simple problem but I'm stumped with a simple select on an HTML5 WebSQL Data Base.
Table tPhones has id, hid, location and several other columns. I would like to return a list of rows with where hid = [input value] or, if no rows with that hid exist, return rows where hid = 1.
I have tried LIMIT 1 ACS etc but that too fails.
Function showPhones(){
var phonegroup = $(this).attr("id");
var hid = localStorage.hid;
db.transaction (function(transaction)
{
var sql = "SELECT * FROM tPhones WHERE dept ='"+phonegroup+"' AND ((hid ='"+hid+"') OR IFNULL (hid ='1')) ORDER BY location ASC";
transaction.executeSql (sql, undefined,function(transaction,result)
{…………..rest of function working fine
Any help would be much appreciated.
A normal expression in the WHERE clause can access only columns of the current record.
To check for the existence of any other record, you have to use a subquery:
SELECT *
FROM tPhones
WHERE dept = ?
AND (hid = ? OR (hid = 1 AND
NOT EXISTS (SELECT 1
FROM tPhones
WHERE dept = ?
AND hid = ?)))
ORDER BY location

SQLite: Selecting the maximum corresponding value

I have a table with three columns as follows:
id INTEGER name TEXT value REAL
How can I select the value at the maximum id?
Get the records with the largest IDs first, then stop after the first record:
SELECT * FROM MyTable ORDER BY id DESC LIMIT 1
Just like the mysql, you can use MAX()
e.g. SELECT MAX(id) AS member_id, name, value FROM YOUR_TABLE_NAME
Try this:
SELECT value FROM table WHERE id==(SELECT max(id) FROM table));
If you want to know the query syntax :
String query = "SELECT MAX(id) AS max_id FROM mytable";

Resources