How to merge 2 condition into 1 line of SQLite? - sqlite

I tried using AND but it didn't work
This is the original code
getAllFeeds(user_id_fk, start) {
let data = [user_id_fk, start]
// ---------this part here ------------------------------------------------------------
return this.database.executeSql("SELECT * FROM feed WHERE (user_id_fk) = (?) ORDER BY feed_id DESC LIMIT ?, 5", data).then((data) => {
// ------------------------------------------------------------------------------------
let feeds = [];
if (data.rows.length > 0) {
for (var i = 0; i < data.rows.length; i++) {
feeds.push({ feed_id: data.rows.item(i).feed_id, feed: data.rows.item(i).feed, user_id_fk: data.rows.item(i).user_id_fk, created: data.rows.item(i).created });
}
}
return feeds;
}, err => {
console.log('Error: ', err);
return [];
});
}
How do I add this?
SELECT DATETIME(created, '+8 hours') as `add8hours` FROM feed WHERE (user_id_fk) = (?) ORDER BY feed_id DESC;
When I use this last line the result will only show the date time and not the other columns
This is the table BTW
CREATE TABLE IF NOT EXISTS feed (
feed_id INTEGER PRIMARY KEY AUTOINCREMENT,
feed TEXT,
user_id_fk INTEGER,
created DATETIME DEFAULT CURRENT_TIMESTAMP
);

If you want to show some specific columns from a table, you need to separate them by a comma.
Eg (using aliases): SELECT COLUMN_1_NAME as ALIAS_COLUMN_1, COLUMN_2_NAME as ALIAS_COLUMN_2 FROM TABLE_NAME;
So in your case it should be something like:
SELECT DATETIME(created, '+8 hours') as add8hours, feed FROM feed WHERE (user_id_fk) = (?) ORDER BY feed_id DESC LIMIT ?, 5

Related

SQLite INSERT OR REPLACE with condition

I have a SQLite database and I'm inserting new records using this query:
INSERT OR REPLACE INTO tags (id, name, color, type, deleted, dirty) VALUES (?, ?, ?, ?, ?, 0)
Id is PRIMARY KEY
If I'm inserting a new record (id doesn't exists in the table) INSERT get executed and everything is fine. If the id already exists then the REPLACE kicks in and the record get replaced. I should add a condition to the REPLACE query: the record should be replaced if and only if dirty is set to 1 in the record already present in the table. How can I add such condition to the query?
This is what i use.
First attempt the update with your condition
then, if not updated, Perform the insert...
Check one example below. calling upsertCategory
/*
* Update a category
*/
public long updateCategory(Category category) {
ContentValues values = new ContentValues();
values.put(COL_CATEGORYDESCRIPTION, category.getDescription());
values.put(COL_CATEGORYSTATUS, category.getStatus());
values.put(COL_CATEGORYCREATEDAT, category.getCreatedAt().getDate());
values.put(COL_CATEGORYUPDATEDAT, category.getUpdatedAt().getDate());
long id = db.update(TABLE_CATEGORIES, values, KEY_ID + "=" + category.getId(), null);
return id;
}
/*
* Update or Insert a category
*/
public long upsertCategory(Category category) {
// update row
long id = updateCategory(category);
// 0 rows affected
if (id == 0) {
// insert row
id = insertCategory(category);
}
return id;
}

How to insert value using textfield to get data in sqlite using appcelerator

I beginner in using appcelerator to develop android apps. I tried to insert data using textfield to retrieve data in sqlite. but if I use example "doc_num.value" with query. I will get error "[ERROR] : V8Exception: Exception occurred at test/csv.js:61: Uncaught TypeError: Cannot read property 'value' of undefined"
var currentWin = Ti.UI.currentWindow;
var label_export = Ti.UI.createLabel({
color:'#fffdfd',
text: 'Please insert document number to export :',
textAlign: Ti.UI.TEXT_ALIGNMENT_CENTER,
top: 20, //200
width: 300,
font:{fontFamily:'Arial',fontSize:14}
});
currentWin.add(label_export);
var doc_num = Ti.UI.createTextField({
color:'#fffdfd',
top:60,
left:10,
width:'80%',
height:40,
hintText:'Document Number',
keyboardType:Ti.UI.KEYBOARD_DEFAULT,
borderStyle:Ti.UI.INPUT_BORDERSTYLE_ROUNDED
});
currentWin.add(doc_num);
// btn search
var btn_search = Ti.UI.createButton({
title:'Export CSV',
top:55, //355
right:5,
width:'15%',
height:50,
color:'green',
borderRadius:1,
font:{fontFamily:'Arial',fontWeight:'bold',fontSize:8}
});
btn_search.addEventListener('click',function(e) {
var db = Ti.Database.install('../products.sqlite','products');
var dbName = db.execute('SELECT doc_num,barcode, product_name,oum,rack_loc,qty FROM products WHERE doc_num = ?',doc_num.value);
while (dbName.isValidRow()) {
var doc_num = dbName.fieldByName('doc_num');
var barcode = dbName.fieldByName('barcode');
var product_name = dbName.fieldByName('product_name');
var rack_loc = dbName.fieldByName('rack_loc');
var oum = dbName.fieldByName('oum');
var qty = dbName.fieldByName('qty');
dbName.next();
Ti.API.info(doc_num + ' ' + barcode + ' ' + product_name+' ' + rack_loc +' '+ oum +' '+qty);
}
dbName.close();
});
currentWin.add(label_warning);
currentWin.add(btn_search);
And this my table structure that I use for my database.Database name products and tape name also products
CREATE TABLE products (id INTEGER PRIMARY KEY, doc_num VARCHAR, product_name VARCHAR, barcode VARCHAR, rack_loc VARCHAR, oum VARCHAR, qty NUMERIC)
You just need to use this line of code instead of yours:
var dbName = db.execute('SELECT doc_num,barcode, product_name,oum,rack_loc,qty FROM products WHERE doc_num = ?', doc_num.value);
You cannot concatenate strings in execute method, you will need to standard approach of passing parameters in SQL query using '?' sign.
Also note that you cannot do this something like this also:
var query = 'select * from products where doc_num = ' + doc_num.value;
This query will fail in case where there are spaces in doc_num.value
So the recommended and safest way of passing values to queries is this:
var query = 'select * from products where doc_num = ? and someother_condition = ?';
db.execute(query, doc_num.value, someother_value);
db.execute method can take any number of parameters starting from 2nd parameter.

SQLite count and get other records in Cordova

Snippet of my code:
var sql = "SELECT name,data, COUNT(name) as 'mycount' FROM floodMaps WHERE name='?' GROUP BY name,data";
db.transaction(function(tx) {
tx.executeSql(sql,[flodMapName], function(tx,res){
//console.log(res.rows.item(0).data);
console.log(res.rows.item(0).mycount);
if(res.rows.item(0).mycount > 0) {
console.log('GETTING DATA FROM DB...');
It throws an error:
a statement with no error handler failed: Cannot bind argument at index 1 because the index is out of range. The statement has 0 parameters.
I am trying to count at the same time get the data from a table but unfortunately it's not working. I did my research, I haven't found a good documentation for the plugin.
This is how I created the table:
document.addEventListener("deviceready", function(){
//database
db = window.sqlitePlugin.openDatabase({name: 'demo.db', location: 'default'});
db.transaction(function(tx) {
tx.executeSql('CREATE TABLE IF NOT EXISTS floodMaps (name text primary key, data text)');
tx.executeSql('DELETE FROM floodMaps');
}, function(error) {
console.log('Create Table ERROR: ' + error.message);
}, function() {
console.log('Table created successfully.');
});
//end database
}, false);
The whole code is here.
I believe that the ? parameter placeholder should not be in single quotes. Try this instead:
var sql = "SELECT name, data, COUNT(name) as `mycount` FROM floodMaps WHERE name= ? GROUP BY name, data";
I guess you need not have to use single quote at all for alias. You can use as follows:
SELECT name,data, COUNT(name) as mycount FROM floodMaps WHERE name=?
Check out this official link that has sample for count query too.

In a Node webkit App, WEB SQL API is not creating a database

I'm creating a database and a table for my node webkit app, using this :
var db = openDatabase('vizDb', '1.0', 'Visualiation database', 2 * 1024 * 1024);
db.transaction(function (tx) {
query = 'CREATE TABLE IF NOT EXISTS dataworking (id, ACV, sales, Date)';
tx.executeSql(query);
$.each(records, function(i,thisRecord){
records[i] = thisRecord.split(',');
query = 'INSERT INTO dataworking (id, ACV, sales, Date) VALUES (' + thisRecord + ')';
//console.log(query); //query is correct here
tx.executeSql(query);
});
});
But when I do the following, I don't get the records in the console.
db.transaction(function (tx) {
query = 'SELECT * FROM dataworking';
tx.executeSql(query , [], function (tx, results) {
var len = results.rows.length ;
for (i = 0; i < len; i++) {
console.log(results.rows.item(i));
}
});
});
I want to check if my records are entered currently. For this, I go to the location
..AppData\Local\Package-name\databases and I see a file Databases.db and a folder file__0 with a file named '1'. I run the SQLite prompt from the location ../file__0/ and list the tables
sqlite>.open 1
sqlite>.tables
sqlite> __WebKitDatabseInfoTable__
But there is no table named dataworking.
How do I open the database vizDb and check if the table 'dataworking' is made?
The Databases.db file contains a list of the actual databases.
Your database is in the file 1.

How to sort in linq to sql for a joined table?

i have these tables in short:
Table: RPG
Coloumns: RPGID, Name
Table: RPGCharacter
Coloumns: CharID, RPGID, Name
Table: RPGPosts
Coloumns: PostID, CharID, Text, timestamp
So in Database the relation is:
1 RPG has X Characters and 1 Character has X Posts.
I get the information with this code:
public static List<RPG> GetAllRPGs()
{
using (RPGDataContext dc = new RPGDataContext())
{
return (from a in dc.RPGs where !a.IsHided && !a.IsDeleted select a).ToList();
}
}
The Problem is:
How to sort these list by the LAST post (TIMESTAMP-Coloumn of the RPGPOst-Table)?
Assuming you've got appropriate navigation properties set up, something like this should work:
var results =
(from a in dc.RPGs
where !a.IsHided && !a.IsDeleted
orderby a.Characters.SelectMany(c => c.Posts).Select(p => p.Timestamp).Max()
select a)
.ToList();
Or possibly:
var results =
(from a in dc.RPGs
where !a.IsHided && !a.IsDeleted
orderby a.Characters
.SelectMany(c => c.Posts)
.OrderByDescending(p => p.Timestamp)
.Select(p => p.Timestamp)
.FirstOrDefault()
select a)
.ToList();

Resources