sqlite / websql: separate queries produce different results than join queries - sql

I have a very simple db that has two tables, one to store a user's auth (username and pw) and one to store preferences. Currently when my app initializes, it checks for settings first and then auth. But I want to grab it all at once. The way the app is designed, there is only ever 1 record in either table, so I don't use WHERE clauses in my queries.
The problem is, when I do queries separately, they give different results than if I join them.
Consider this scenario: a user logs in, sets some settings and then logs out. In may app this causes the auth table to be cleared but the settings remain intact.
Sign-out query (just clears auth table)
db.transaction(function(tx) {
tx.executeSql('DELETE FROM userdata');
}, errorDB);
However this outputs "0 rows found":
db.transaction(function(tx) {
tx.executeSql('SELECT USERDATA.*, PREFS.* FROM USERDATA, PREFS', [], function (tx, results) {
var len = results.rows.length;
console.log(len + " rows found.");
for (var i=0; i<len; i++){
console.log("Row = " + i + " ID = " + results.rows.item(i).id + " Data = " + results.rows.item(i));
}
}, errorDB);
}, errorDB);
Whereas this outputs a row:
db.transaction(function(tx) {
tx.executeSql('SELECT * FROM PREFS', [], function (tx, results) {
var len = results.rows.length;
console.log(len + " rows found.");
for (var i=0; i<len; i++){
console.log("Row = " + i + " ID = " + results.rows.item(i).id + " Data = " + results.rows.item(i));
}
}, errorDB);
}, errorDB);
Even if there is no auth shouldn't the join query find the prefs data? What's going on here?

When you list two tables A and B in the FROM clause, you get a cross join, which returns A×B records.
So if one table is empty, the result will be empty, too.
To ensure that you have a record even for an empty table, add another record with UNION ALL, then use LIMIT 1 return the first record.
For example,
SELECT Name, PW FROM UserData
UNION ALL
SELECT NULL, NULL
LIMIT 1
will return either a single record with the name/password, or a single record with two NULL values.
To join that with the other table, use a subquery:
SELECT *
FROM (SELECT Name, PW FROM UserData
UNION ALL
SELECT NULL, NULL
LIMIT 1),
Prefs

Related

Return values of #All of functions in podio calculation fields

I have 5 contacts connected to a company, and i am trying to sort out the ones that does not have an email with the code below.
var mailArray = #All of Email with nulls
var temp = new Array()
for (var i = 0; i < mailArray.length; i++) {
if (mailArray[i].value == null) {
temp.push("null")
}
else {
temp.push("correct")
}
}
temp.join(" ")
Right now i am just pushing the strings to make sure that the flow is correct, it however returns
null null null null null
when it should return
null correct correct null null
since the second and third contact has emails. Can anyone help me or give me a hint, as how to use the return value of the #All of function.
I just want to make sure what you are referring to on the emails. Is it an email field in the contacts app, or is it a text field that is called 'email'? If you are using an email field, then the value at your [i] index is actually another object and not just a string yet. Although it doesn't matter if you are just checking for something existing, but personally I'd like to know which contacts do have emails in the output.
If it is just a text field, then you have a problem with the conditional statement. It should be === instead of ==, but I would personally just rewrite it as !mailArray[i].
I'd recommend changing your output to be a markdown table for legability. Here's the code I ended up with:
var mailArray = #All of Email text with nulls
var nameArray = #All of Name with nulls
var temp = new Array()
var table = "Email | Contact \n --- | --- "
for (var i = 0; i < mailArray.length; i++) {
if (!mailArray[i].value){// !== null) {
temp.push("correct")
temp.push(mailArray[i])
table +="\n"+ mailArray[i] + " | " + nameArray[i]
}
else {
temp.push("null")
table +="\n"+ mailArray[i] + " | " + nameArray[i] + "\n"
temp.push(mailArray[i])
}
}
temp.join(" ")
write = table
And this outputs the following table (made 3 contacts, 2 with emails and one without):

SQLite with Android Studio, return all records selected by 2 arguments

let's assume that i have a table with columns such as:
ID SSID BSSID RSSI
1 abcd hs:hd:sd -60
2 abcd hs:hd:po -68
There are about 5000 records with the same SSID, slighltly different BSSID and the LEVEL values. My device is scanning the nearest environment for WiFi networks, therefore I know their MAC address and level of RSSI. I pick 3 with the highest value od RSSI.
First thing I would like to know if it is possible to search through the database to get all the records with the LEVEL value equal or close to 60, for instance 59,58,61.
Secondly, is there a way to query the database to return all the records with the same MAC addresses and RSSI values as from the 3 best scan result? If so, how would that query look like?
EDIT: Thanks for all the answers. What I'm trying to do now is to compare 3 scans with records stored in database with getRequiredData function. I would like to pass 2 parameters to this function, mac address and level and find records with same value for both parameters. The rawQuery seems to be fine, code is compiling but the app is crashing with the first scan. I cant find the cause of it, is it because my logic of getting these parameters is wrong or does it have something to do with query?
public Cursor getRequiredData(String mac, int level){
SQLiteDatabase db = this.getWritableDatabase();
Cursor res = db.rawQuery("SELECT BSSID, RSSI FROM TABLE_NAME WHERE BSSID =? AND RSSI=?", new String[] {mac, level});
return res;
}
scan part:
class WifiReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
sb = new StringBuilder();
Comparator<ScanResult> comparator = new Comparator<ScanResult>() {
#Override
public int compare(ScanResult o1, ScanResult o2) {
return (o1.level>o2.level ? -1 : (o1.level==o2.level ? 0 : 1));
}
};
lista = wifiManager.getScanResults();
Collections.sort(lista, comparator);
for (int i = 0; i < lista.size(); i++) {
scanResult = wifiManager.getScanResults().get(i);
sb.append(new Integer(i + 1).toString() + ". " + (lista.get(i)).SSID + " " + (lista.get(i)).BSSID + " " + (lista.get(i)).level + "\n");
boolean isInserted = myDb.insertData(lista.get(i).SSID.toString(), lista.get(i).BSSID.toString(), lista.get(i).level);
if (isInserted = true)
Toast.makeText(MainActivity.this, "Data inserted", Toast.LENGTH_LONG).show();
else
Toast.makeText(MainActivity.this, "Data not inserted", Toast.LENGTH_LONG).show();
}
for (int i=0; i<4; i++)
{
scanResult = wifiManager.getScanResults().get(i);
match = myDb.getRequiredData(lista.get(i).BSSID.toString(), lista.get(i).level);
}
Log.i("match values: ", DatabaseUtils.dumpCursorToString(match));
txt.setText(sb);
wifiManager.startScan();
}
}
Here is what match contains:
2018-12-10 16:36:26.334 13347-13347/com.example.maciek.wifiscann I/match values:: >>>>> Dumping cursor android.database.sqlite.SQLiteCursor#e1a86d1
0 {
BSSID=f4:c5:ed:5c:s6:20
RSSI=-69
}
1 {
BSSID=f4:c5:ed:5c:s6:20
RSSI=-69
}
2 {
BSSID=f4:c5:ed:5c:s6:20
RSSI=-69
}
3 {
BSSID=f4:c5:ed:5c:s6:20
RSSI=-69
}
4 {
BSSID=f4:c5:ed:5c:s6:20
RSSI=-69
}
5 {
BSSID=f4:c5:ed:5c:s6:20
RSSI=-69
}
<<<<<
To get the 3 rows with the closest values to 60 in column LEVEL:
SELECT * FROM tablename ORDER BY ABS(LEVEL - 60), LEVEL LIMIT 3
For the 2nd part of your question, you should provide sample data of the table. Edit:
From the sample data that you posted I don't see a column RSSI, but if it exists in the table then the SELECT statement is ok.
Change the 2nd parameter of rawQuery() to:
new String[] {mac, String.valueOf(level)}
because level is int.
In onReceive() you use myDb. I don't know how you initialize it.
If the app crashes you must copy the log, the part that identifies the problem and post it.
First thing I would like to know if it is possible to search through
the database to get all the records with the LEVEL value equal or
close to 60, for instance 59,58,61.
SELECT * FROM your_table WHERE level BETWEEN 59 AND 61;
where your_table is the respective table name.
Note if levels are negative (as per example data) then BETWEEN requires the lowest value first so it would be BETWEEN -61 AND -59.
Secondly, is there a way to query the database to return all the
records with the same MAC addresses and RSSI values as from the 3 best
scan result? If so, how would that query look like?
SELECT * FROM your_table WHERE your_mac_address_column = 'the_mac_address_value' AND RSSI = 'the_rssi_value' ORDER BY LEVEL DESC LIMIT 3
Note the above assumes that the MAC address is stored in a column (if NOT then cannot be done unless the mac address can be correlated to a column).
Assumes best LEVEL is lowest so -1 is better than -60 (if not then use ASC instead of DESC)
Again your_table, your_mac_address_column, the_mac_address_value and the_rssi_value would be replaced accordingly with actual values (note that strings should be in single quotes).

MERGE INTO multiple statements at once Oracle SQL

I have a merge into statement as this :
private static final String UPSERT_STATEMENT = "MERGE INTO " + TABLE_NAME + " tbl1 " +
"USING (SELECT ? as KEY,? as DATA,? as LAST_MODIFIED_DATE FROM dual) tbl2 " +
"ON (tbl1.KEY= tbl2.KEY) " +
"WHEN MATCHED THEN UPDATE SET DATA = tbl2.DATA, LAST_MODIFIED_DATE = tbl2.LAST_MODIFIED_DATE " +
"WHEN NOT MATCHED THEN " +
"INSERT (DETAILS,KEY, DATA, CREATION_DATE, LAST_MODIFIED_DATE) " +
"VALUES (SEQ.NEXTVAL,tbl2.KEY, tbl2.DATA, tbl2.LAST_MODIFIED_DATE,tbl2.LAST_MODIFIED_DATE)";
This is the execution method:
public void mergeInto(final JavaRDD<Tuple2<Long, String>> rows) {
if (rows != null && !rows.isEmpty()) {
rows.foreachPartition((Iterator<Tuple2<Long, String>> iterator) -> {
JdbcTemplate jdbcTemplate = jdbcTemplateFactory.getJdbcTemplate();
LobCreator lobCreator = new DefaultLobHandler().getLobCreator();
while (iterator.hasNext()) {
Tuple2<Long, String> row = iterator.next();
String details = row._2();
Long key = row._1();
java.sql.Date lastModifiedDate = Date.valueOf(LocalDate.now());
Boolean isSuccess = jdbcTemplate.execute(UPSERT_STATEMENT, (PreparedStatementCallback<Boolean>) ps -> {
ps.setLong(1, key);
lobCreator.setBlobAsBytes(ps, 2, details.getBytes());
ps.setObject(3, lastModifiedDate);
return ps.execute();
});
System.out.println(row + "_" + isSuccess);
}
});
}
}
I need to upsert multiple of this statement inside of PLSQL, bulks of 10K if possible.
what is the efficient way to save time : execute 10K statements at once, or how to execute 10K statements in the same transaction?
how should I change the method for support it?
Thanks,
Me
the most efficient way would be one that bulk-loads your data into the database. In comparison to one-by-one uploads (as in your example), I'd expect performance gains of at least 1 or 2 orders of magnitude ("bigger" data means less to be gained by bulk-inserting).
you could use a technique as described in this answer to bulk-insert your records into a temporary table first and then perform a single merge statement using the temporary table.

Get value from Titanium Appcelerator db column

I've looked around everywhere, but I can't seem to find exactly what I'm trying to do. It should be fairly simple...
I have a db table set up like this:
var db = Ti.Database.open('playerInfo.db');
db.execute('CREATE TABLE IF NOT EXISTS playersTable (id INTEGER PRIMARY KEY, name TEXT NOT NULL, "50" INTEGER, "25" INTEGER )');
I have two buttons with an assigned value of 25, and 50, respectively. Each button has a "value" key, where I assign their values. I am trying to accomplish three things:
When a button is pressed, find the column of corresponding value.
increase the value of this column by 1.
Retrieve the new value and console log it.
This is what my code looks like when a button is pressed:
var rows = db.execute("SELECT '" + button.value + "' FROM playersTable WHERE name= '" + owner + "'");
var imagesString = rows.fieldByName(button.value);
Ti.API.debug(imagesString)
This is all in a click event listener where the variable "owner" is passed in as a string.
This is the error I get:
message = "Attempted to access unknown result column 25";
I don't have too much experience with sql, so I'm not sure what I'm doing right and what I'm doing wrong. Any help is appreciated!
Thanks.
I'm not sure quite exactly what the problem is, but the following works for me. Note that the "?" variable substitution syntax makes sure that the values are quoted properly for MySQL:
button = e.source;
db = Titanium.Database.open('test');
var rows = db.execute("SELECT * FROM playersTable WHERE name= ?", "foo");
// Theoretically this should be returning a single row. For other results,
// we would loop through the result set using result.next, but here just check if
// we got a valid row.
if (rows.isValidRow()) {
var imagesString = rows.fieldByName(button.value);
var id = rows.fieldByName('id');
imagesString = imagesString + 1;
Ti.API.info("id = " + id + " val = " + imagesString);
// The ? substitution syntax doesn't work for column names, so we
// still need to stick the button value into the query string.
db.execute('UPDATE playersTable set "' + button.value +'"= ? where id = ?', imagesString, id);
}
else
{
Ti.API.info("Row not found.");
}
db.close();
If you get the row not found error, it's possible your data isn't getting inserted properly in the first place. Here's how I inserted my test row for player "foo":
db.execute('insert into playersTable (name, "50", "25") values (?,?,?)', 'foo', 0, 0);
I think this should solve your problem. Let me know if this doesn't work for you.

query.next() returning false

I have used the query.next() function inside my code, but its returning false.
I even checked in the database, there are 4 records present. But the code shows only one.
However if i use query.next() before the code of query.valid() then it doesn't show any record
Please help
qDebug() << "entering payment: get all the unchecked invoices for user: " + user;
QStringList tmp;
QSqlQuery query(m_storageUserManager->database());
m_storageUserManager->dumpTable(m_invoiceInfoTable);
m_storageUserManager->dumpTable(m_invoiceUserTable);
qDebug()<<"THE NAME OF THE INVOICE USER TABLE_----=-----------------"<<m_invoiceInfoTable;
qDebug()<<"THE NAME OF THE INVOICE USER TABLE_----=-----------------"<<m_invoiceUserTable;
query.prepare("SELECT invoice FROM "+ m_invoiceInfoTable +" WHERE invoice = (SELECT
invoice FROM "+ m_invoiceUserTable +" WHERE user=:user)");
// query.prepare("SELECT invoice FROM " + m_invoiceInfoTable + ","+ m_invoiceUserTable +" WHERE " + m_invoiceInfoTable + ".user = " + m_invoiceUserTable + ".:user");
query.bindValue(":user", user);
query.exec();
query.first();
qDebug()<<"Unchecked invoices done!!! " ;
if(query.isValid()) {
do {
tmp.append(query.value(0).toString()); //as the value returned by value() is a QVariant so we need to change it to String.
} while(query.next());
} else
tmp.append("No Unchecked invoice in the database");
return tmp;
To check if the query was successful you should test the return value of either QSqlQuery::exec() or QSqlQuery::isActive() before trying to call first/next/last (when you pass the query string to the constructor of QSqlQuery, the query is already executed, so, you need to use QSqlQuery::isActive()).
first(), next() and last() return true if they positioned the query on a valid record, you don't have to test isValid() separately. Since first() is a positioning function too, you can read the value without calling next() directly after, unless you want to skip the first record.
Since you may want to add fields from the the "invoice-info" table to your query, I kept the subquery (with IN instead of = as Mat already answered in the comment).
query.prepare(QString("SELECT invoice FROM %1 WHERE invoice "
"IN (SELECT invoice FROM %2 WHERE user=:user)")
.arg(m_invoiceInfoTable, m_invoiceUserTable));
/*
// Or with an inner join
query.prepare(QString("SELECT %1.invoice FROM %1 "
"INNER JOIN %2 ON %1.invoice = %2.invoice "
"WHERE user=:user").arg(m_invoiceInfoTable, m_invoiceUserTable));*/
query.bindValue(":user", user);
if (!query.exec()) {
tmp.append("Query error: %1" + query.lastError().text());
} else if (!query.first()) {
tmp.append("No Unchecked invoice in the database");
} else {
do {
tmp.append(query.value(0).toString());
} while(query.next());
}
Try
query.prepare("SELECT invoice FROM " + m_invoiceInfoTable + " WHERE user=:user");