Variable Names with Node SQLite [duplicate] - javascript

From the npm docs, only visible prepared statements are for insert. Does these prepared statement work for Select, update, and delete?
I tried for select, there isn't a .each function where the rows are called back. Anyone been able to do this or have links to resources, cause I can sure as hell unable to find any.

According to the node-sqlite3 API documentation, you can use parameters in your SQL queries in several different ways:
// Directly in the function arguments.
db.run("UPDATE tbl SET name = ? WHERE id = ?", "bar", 2);
// As an array.
db.run("UPDATE tbl SET name = ? WHERE id = ?", [ "bar", 2 ]);
// As an object with named parameters.
db.run("UPDATE tbl SET name = $name WHERE id = $id", {
$id: 2,
$name: "bar"
});

Yes, prepared statements are supported.
With node-sqlite3:
var sqlite3 = require('sqlite3').verbose();
var db = new sqlite3.Database('data.db');
db.serialize(function() {
var stmt = db.prepare("INSERT INTO users VALUES (?,?)");
for (var i = 0; i < 10; i++) {
stmt.run("user " + i, "email " + i);
}
stmt.finalize();
stmt = db.prepare("SELECT * FROM users WHERE id=?");
stmt.each(userId, function(err, row) {
console.log(row.name, row.email);
}, function(err, count) {
stmt.finalize();
});
});
With better-sqlite3:
var Database = require('better-sqlite3');
var db = new Database('foobar.db', options);
var stmt = db.prepare("INSERT INTO users VALUES (?,?)");
for (var i = 0; i < 10; i++) {
stmt.run("user " + i, "email " + i);
}
var stmt = db.prepare('SELECT * FROM users WHERE id=?');
var row = stmt.get(userId);
console.log(row.name, row.email);

Related

Trouble accessing javascript objects within array

I have some kind of error in my javascript that I can't seem to figure out. I am creating objects of cars out of a MySql query. Further I am storing these objects into an array (carArray).
The problem seems to appear once I try to access these objects later on. In this example, I want to present the objects within a table.
function AddTableOfCars(){
// Table headers
var heading = new Array();
heading[0] = "Merke";
heading[1] = "Reg.nr.";
heading[2] = "Sist endret";
// Database connection
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'db_host',
user : 'db_user',
password : 'db_password',
database : 'db_name'
});
// Empty array to store cars
var carArray = [];
connection.connect();
var stmt = 'SELECT `VehicleID`,`VehicleMake`,`LicenseNumber`,`IsActive`,`DateChanged` FROM `db_table`';
connection.query(stmt, function (error, rows, fields) {
if (error) console.log(error.code);
else {
// Loop through query result
// Create car objects
// Store car objects in array
for (var i = 0; i < rows.length; i++) {
var carObj = new Car(rows[i].VehicleID, rows[i].VehicleMake, rows[i].LicenseNumber, rows[i].IsActive, rows[i].DateChanged);
carArray.push(carObj);
}
}
});
connection.end();
// Table columns
var table = document.getElementById('car-table');
for (var i = 0; i < carArray.length; i++) {
var row = table.insertRow(i);
var cellMake = row.insertCell(0);
var cellLicense = row.insertCell(1);
var cellDateChanged = row.insertCell(2);
cellMake.innerHTML = carArray[i].VehicleMake;
cellLicense.innerHTML = carArray[i].LicenseNumber;
cellDateChanged.innerHTML = carArray[i].DateChanged;
}
// Logs for debugging purposes
console.log(carArray);
console.log(carArray[0]);
}
My console.log(carArray); returns the following within the console:
[]
0: Car
1: Car
length: 2
So far, it seems to add up. However, when I try to access one of the objects within the array using console.log(carArray[0]);, it returns undefined.
Does anyone have any pointers for me at this point. It's most likely just a tiny detail that I have missed. But I have been looking at my code for quite some time now, I am starting to see animals instead of code...
Any help would be greatly appreciated.
I think you might be experiencing some Async issues. See if this sorts it:
function AddTableOfCars() {
let tableHeaders = ["Merke", "Reg.nr.", "Sist endret"];
let mysql = require('mysql');
let stmt = 'SELECT `VehicleID`,`VehicleMake`,`LicenseNumber`,`IsActive`,`DateChanged` FROM `db_table`';
let connection = mysql.createConnection({
host: 'db_host',
user: 'db_user',
password: 'db_password',
database: 'db_name'
});
connection.connect();
connection.query(stmt, function (error, rows) {
if (error) {
console.log(error.code);
} else {
let carArray = [];
rows.forEach(row => {
carArray.push(new Car(row.VehicleID,
row.VehicleMake,
row.LicenseNumber,
row.IsActive,
row.DateChanged));
});
buildTable(carArray);
}
});
connection.end();
}
function buildTable(carArray){
// Table columns
var table = document.getElementById('car-table');
carArray.forEach(car => {
var row = table.insertRow(i);
var cellMake = row.insertCell(0);
var cellLicense = row.insertCell(1);
var cellDateChanged = row.insertCell(2);
cellMake.innerHTML = car.VehicleMake;
cellLicense.innerHTML = car.LicenseNumber;
cellDateChanged.innerHTML = car.DateChanged;
});
}
Note: I couldn't see your use of tableHeaders but I left it in anyway.

Cordova Sqlite plugin inserts entries with null values

I'm implementing the Cordova Sqlite plugin in a Ionic project, so far I've been able to create a database and table and make queries following the functions available through the ngCordova implementation.
I noticed there's a insertCollection function available, which I tried to test, I passed an array to it and even though the inserts are made, the entries are made with null.
This my example table definition:
CREATE TABLE IF NOT EXISTS people (id integer primary key, firstname text, lastname text)
I filled an array like this:
for(var i = 0; i < 250000; i++){
var index = i + 1;
firstname = firstname + ' ' + index;
var entry = {
'firstname' : firstname,
'lastname' : lastname
};
$scope.insertArray.push(entry);
}
And then made the insert like this:
$cordovaSQLite.insertCollection($rootScope.db, $scope.insertQuery, $scope.insertArray).then(function(res) {
console.log(res);
}, function (err) {
console.error(err);
});
Where insertQuery is the following:
INSERT INTO people (firstname, lastname) VALUES (?,?)
I made a select like this:
$scope.select = function() {
$scope.results = [];
var query = "SELECT firstname, lastname FROM people";
$cordovaSQLite.execute($rootScope.db, query).then(function(res) {
if(res.rows.length > 0) {
console.log('select was successful ' + res.rows.length + ' entries');
for(var i = 0; i < $scope.maxItemsToShow; i++){
$scope.results.push(res.rows.item(i));
}
} else {
console.log("No results found");
}
}, function (err) {
console.error(err);
});
}
I try to display the results on a ion-list but the values in firstname and lastname are null for all the items.
What is causing this problem?
The function insertCollection expects an array of arrays, not an array of records. The inner array must contain the values to insert in the order that the question marks (as place holders for the values) appear in the sql statement.
So you need to write:
for(var i = 0; i < 250000; i++){
var index = i + 1;
firstname = firstname + ' ' + index;
var entry = [firstname, lastname];
$scope.insertArray.push(entry);
}

Group By Query in Parse.com Cloud Code

I'm trying to get the results of the following sql command in Parse.com using cloud code.
Select shop, count(1) from Membership group by shop;
Is there a way to do so? or I can only get the number of members from selecting each shop?
var query = new Parse.Query("Membership");
query.equalTo("shop",shop_id);
var promise = query.find().then(function(results){
var number_of_membership_of_one_shop = results.leng
return results;
});
Parse unfortunately doesn't support group by.
You could first select all shops and then use a count query for each shop.
var query = new Parse.Query("Membership");
query.equalTo("shop",shop_id);
var promise = query.count().then(function(count){
var number_of_membership_of_one_shop = count;
return number_of_membership_of_one_shop;
});
If this is performing too many requests, you could select all the memberships and then count them on the client, but this will have a limit of 1000 so you may need to adopt some other techniques:
var query = new Parse.Query("Membership");
query.select("shop_id");
query.limit(1000);
var storeCounts = [];
queryObject.find({
success: function (results) {
for (var i = 0; i < results.length; i++) {
var shopId = results[i].get('shop_id');
if (!storeCounts[shopId]) {
storeCounts[shopId] = 0;
}
storeCounts[shopId]++;
}
},
error: function (error) {
alert("Error: " + error.code + " " + error.message);
}
});

Retrieving Data from existing database using webSQL?

i'm trying to retrieve the data from the database for web application using webSQL ,but i'm unable to get the data from database. I'm very new to this. I tried like this
var DB_NAME = "database";
var DB_VERSION = "";
var DB_TITLE = "";
var DB_BYTES = 50 * 1024 * 1024;
var db = openDatabase(DB_NAME, DB_VERSION, DB_TITLE, DB_BYTES);
//Retrieve Rows from Table
db.transaction(
function(tx) {
tx.executeSql("SELECT * FROM Data;",
[],
function (tx, results) {
var len = results.rows.length, i;
for (i = 0; i < len; i++) {
alert(results.rows.item(i).text);
}
});
});
Thanks in Advance.
This is how i have done.. and this is working for me.
// global variables
var db;
var shortName = 'Books';
var version = '1.0';
var displayName = 'BooksDB';
var maxSize = 200000;//65535;
function ListDBValues() {
if (!window.openDatabase) {
alert('Databases are not supported in this browser.');
return;
}
// this line tries to open the database base locally on the device if it does not exist, it will create it and return a database object stored in variable db
db = openDatabase(shortName, version, displayName,maxSize);
// this line clears out any content in the #lbUsers element on the page so that the next few lines will show updated content and not just keep repeating lines
$('#lbUsers').html('');
// this next section will select all the content from the User table and then go through it row by row appending the UserId FirstName LastName to the #lbUsers element on the page
db.transaction(function(transaction) {
transaction.executeSql('SELECT * FROM books;', [], function(transaction, result) { if (result != null && result.rows != null) { for (var i = 0; i < result.rows.length; i++) { var row = result.rows.item(i); $('#lbUsers').append('<br>' + row.book_title + '. ' + row.book_isbn+ ' ' + row.book_price); } } },errorHandler); },errorHandler,nullHandler);
return;
alert('in list end');
}
// this is called when a successful transaction happens
function successCallBack() {
alert("DEBUGGING: success");
}
function nullHandler(){
alert('null handler');
};

Web db - getting the data back

Here is the code
onError = function(tx, e) {
alert('Something unexpected happened: ' + e.message );
}
var webdb = openDatabase(dbName, '1.0' , dbDesc , dbSize);
var colourArray = new Array();
webdb.transaction(function(tx) {
tx.executeSql('SELECT * FROM colours',
[],
function(tx,rs) {
var ctn = rs.rows.length;
for (var i=0; i < ctn; i++) {
var row = rs.rows.item(i);
colourArray.push([row.id , row.title]);
}
},
onError);
});
/**
* the array looks like [[1,'red'],[2,'white'],[3,'black'] ...]
*/
var ColourStore = new Ext.data.ArrayStore({fields: ['key', 'val'],
data: colourArray});
The table "colours" contain colour name and hash code. And it was suppose to be use by a ExtJS Ext.data.ArrayStore then populate other drop downs on a massive form.
My problem is - I couldn't get the data back as an array. The variable "colourArray" is empty ... I know I hit some javascript closure , loop problem ... but just couldn't figure out how to get that inner loop value back. Try a lot of return -> return -> return function and more return. None of them works.
executeSQL is asynchronous. You need to create ColourStore in the function(tx,rs) callback function. If you need the data available globally, you can't init your app until executeSQL calls the callback function. Example:
Ext.onReady( function() {
var webdb = openDatabase(dbName, '1.0' , dbDesc , dbSize);
var colourArray = new Array();
var ColourStore;
webdb.transaction( function(tx) {
tx.executeSql('SELECT * FROM colours',
[], function(tx,rs) {
var ctn = rs.rows.length;
for (var i=0; i < ctn; i++) {
var row = rs.rows.item(i);
colourArray.push([row.id , row.title]);
}
//INIT YOUR APP HERE IN ORDER TO HAVE ACCESS TO colourArray values
ColourStore = new Ext....
YourApp.init();
},
onError);
});
}, this);

Categories