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

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.

Related

How to merge 2 condition into 1 line of 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

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.

Titanium: SQL Lite "Attempted to access unknown result column time"

I'm getting this error when trying to execute a SQL Lite query:
"Attempted to access unknown result column time"
The SQL in question is:
var db = Ti.Database.open('spacev3');
var tRS = db.execute('SELECT time(vreme) FROM locdb ORDER BY ID DESC');
while (tRS.isValidRow())
{
var ttime = tRS.fieldByName('time');
Ti.API.info('ttime=' + ttime);
tRS.next();
}
tRS.close();
According to SQL lite specs, that should work?
The DB Schema is:
CREATE TABLE IF NOT EXISTS locdb (id INTEGER PRIMARY KEY, lat TEXT, lon TEXT, alt TEXT, speed TEXT, vreme TEXT);
Any ideas?
try this,
var tRS = db.execute('SELECT time(vreme) as time FROM locdb ORDER BY ID DESC');

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.

Selected value from dropdownlist has to be tablename from linq query

I have a problem with my linq query. I want a search field (textbox) with a dropdownlist next to it. When i set the dropdownlist on "ProductID" he has to search only in the table "ProductID", And when i put it on "Productinformation", he has to search in the table "productinformation", i hope somebody understand this?
So what i want is the following query:
var textboxvalue = TextBox1.Text;
var dropdownsearch = DropDownList1.SelectedValue;
var Metadata = from m in db.Metadatas
join mm in db.Multimedias
on m.multimediaID equals mm.multimediaID
where (m. {{{Here i want the dropdownsearch}}} .ToString().Contains(textboxvalue) ||
mm. {{{Here i want the dropdownsearch}}} .ToString().Contains(textboxvalue))
select new
{
mm.ProductID,
mm.filename,
mm.filetype,
mm.filesize
};
So, how can i get the selected value from the dropdownlist, as a table in the query? Normally you would put m.ProductID into the query, but i want the Selected value in it, something like m.(Dropdownlist1.Selectedvalue)... or m.dropdownsearch..
Is that possible? And how?
Thanks :)
var Metadata = from m in db.Metadatas
join mm in db.Multimedias
on m.multimediaID equals mm.multimediaID
select new { m, mm };
var filtered = Metadata.Where("m." + dropdownsearch + " like '#0'", textboxvalue);
var filtered = Metadata.Where("mm." + dropdownsearch + " like '#0'", textboxvalue);
var result = filtered.Select(f => new
{
f.mm.ProductID,
f.mm.filename,
f.mm.filetype,
f.mm.filesize
};

Resources