I am having trouble trying to add a JS Object into an sqlite database. I am using cordova, creating an app for android, windows and iOS.
I have this code for my insert and retrieval...
var data = localStorage.getItem('folderData');
console.log(data);
var username = localStorage.getItem("username");
var session = localStorage.getItem("session_ID");
tx.executeSql('CREATE TABLE IF NOT EXISTS folderData (id integer primary key autoincrement, username, sessionID, folderData text)');
tx.executeSql('SELECT * FROM folderData WHERE username = "'+username+'"', [], function(tx, result) {
if(result.rows.length > 0){
tx.executeSql('UPDATE folderData SET folderData = "'+data+'", sessionID = "'+session+'" WHERE username = "'+username+'"');
alert('An update has occured folderData');
} else {
tx.executeSql('INSERT INTO folderData (username, sessionID, folderData) VALUES ("'+username+'", "'+session+'", "'+data+'")');
alert('An insert has occured folderData');
}
});
tx.executeSql('SELECT folderData FROM folderData WHERE username = "'+username+'" AND sessionID = "'+session+'" ORDER BY id desc LIMIT 1', [], function(tx, result) {
querySuccessFolderData(tx, result);
});
The data variable is my object. When I console.log(data) before insertion i get the following
This my querySuccessFolderData function
function querySuccessFolderData(tx, results) {
var len = results.rows.length;
//alert("folderData table: " + len + " rows found.");
var newFolderData = jsonParse(results.rows.item(0).folderData);
for(i=0;i<len;i++)
{
var newFolderData = results.rows.item(i).folderData;
}
console.log(newFolderData);
}
console.log(newFolderData); now shows up as [Object Object]
What am I doing wrong? Do i need to convert the object again after I select it from the database? This is becoming a nightmare for me now, i've been looking at it for way too long. Any help would be much appreciated.
Managed to fix my issue.
Set my localStorage data.
localStorage.setItem("folderData", JSON.stringify(data['root']));
Used getItem to retrieve it in another function and encoded it for the database insert
var data = localStorage.getItem('folderData');
data = encodeURI(data);
Then used decodedURI and jsonParse to turn it back into an object
var newFolderData = results.rows.item(0).folderData;
newFolderData = decodeURI(newFolderData);
newFolderData = jsonParse(newFolderData);
Which gave me the correct data saved.
Related
I have a stored procedure that returns two tables data. While I am executing stored procedure from the server side script I got tow tables data together as individual rows.
But on response I couldn't figure out which row belongs to which table.
Can anyone help me to solve this
Here is my code
server.js
var pool = new ConnectionPool(poolConfig, config);
var sqlGet = "exec dbo.getTableData";
var data = [];
pool.acquire(function (err, tconnection) {
if (err) {
console.error(err);
return;
}
var request = new Request(sqlGet, function(err, result){
tconnection.release();
if(err)
console.log(err);
res.send(data);
});
request.on('row', function(columns) {
var row = {};
columns.forEach(function(column) {
row[column.metadata.colName] = column.value;
});
data.push(row);
});
tconnection.execSql(request);
});
My Stored procedure code:
CREATE PROCEDURE [dbo].[getTableData]
AS
SELECT * FROM table1;
SELECT * FROM table2;
RETURN
On below code I get list of columns returning from stored procedure, on column I got this response
request.on('row', function(columns) {
var row = {};
columns.forEach(function(column) {
row[column.metadata.colName] = column.value;
});
data.push(row);
});
Thanks #PrashanthReddyBalemula, As from his comment, I solved my problem by returning table name from the stored procedure
CREATE PROCEDURE [dbo].[getTableData]
AS
SELECT *, 'MyTable1' as TableName FROM table1;
SELECT *,'MyTable2' as TableName FROM table2;
RETURN
By this I can get the table's name from the field TableName
Hello I have database and queries written in a module and I am calling the module from the main class. What I want is to pass a query in function and get results. This is what I am doing so far
database.js
var pool = mysql.createPool({
host : 'localhost',
user : 'xxxx',
password : 'xxx',
database : 'xxx'
});
exports.executeQuery=function(query,callback){
pool.getConnection(function(err,connection){
if (err) {
console.log("error comes " + err);
callback(true);
return;
}
connection.query(query,function(err,results){
connection.release();
if(!err) {
console.log("no error");
callback(false,{rows: results});
}
// check null for results here
});
connection.on('error', function(err) {
callback(true);
return;
});
});
};
and in my main class
var db = require('./database');
var user_id = 5
var query = "SELECT * FROM contacts WHERE user_id = ?", user_id;
db.executeQuery(query, function(r,contact_details) {
console.log("success");
console.log(contact_details);
});
It doesn't work. It doesn't even go inside the function or prints success string. But If I do query this
var query = "SELECT * FROM contacts";
This will work. But I want to send a conditional query and because of conditional query, it doesn't work. Don't know how to send a conditional query, for example, this query
var query = "SELECT * FROM contacts WHERE user_id = ?", user_id;
or
"SELECT count(*) as count FROM user_info WHERE user_id = ? AND phone_no_1 = ? OR phone_no_2 = ? OR phone_no_3 = ?",[user_id,formatted_sms_no,formatted_sms_no,formatted_sms_no],
These kind of queries. Any help would be appreciated.
Thank you
As far as I see in module mysql you have the feature called preparing queries.
So basically you should pass query and parameters for executing, f.e. your function definition will look like this function(query, parameters, callback), and than use mysql.format(query, parameters) before executing the query.
I have an array of customer objects, that I wish to insert to the SQL database.
The customer objects are retrieved from the req data.
I am using Tedious for the request, and Tedious Connectionpool in order to have multiple connections at the same time.
When looping over the objects i am getting an error when trying to insert, the error being
{ [RequestError: Violation of PRIMARY KEY constraint `'PK__Customer__A4AE64D873A5400C'. Cannot insert duplicate key in object 'dbo.Customer'. The duplicate key value is (2).]`
Note that I only have 3 object being send in the req at this time. It looks to me that it is only the last object that are being handled and inserted. But since I am new to using tedious with Node.js i cant spot my mistake. Any suggestions ?
router.post('/',jsonParser, function(req, res) {
var customers = req.body.customers;
var companies = req.body.companies;
var Connection = require('tedious').Connection;
var Request = require('tedious').Request;
var TYPES = require('tedious').TYPES;
var config = {
userName: '*************',
password: '*************',
server: '***********.database.windows.net',
// When you connect to Azure SQL Database, you need these next options.
options: {encrypt: true, database: '*******'}
};
var poolConfig = {
min: 1,
max: 3,
log: true
};
var pool = new ConnectionPool(poolConfig, config);
for (var i = 0; i < customers.length; i++) {
console.log('Inserting '+customers[i].firstname);
var firstname = customers[i].firstname;
var count = i;
pool.acquire(function (err, connection) {
if (err)
console.error(err);
//use the connection as normal
var request = new Request("INSERT INTO dbo.Customer" +
" (Firstname,CustomerId)" +
"VALUES" +
" (#Firstname,#CustomerId);", function (err, rowCount) {
if (err)
console.error(err);
console.log('rowCount: ' + rowCount);
//release the connection back to the pool when finished
connection.release();
});
request.addParameter('Firstname', TYPES.VarChar,firstname);
request.addParameter('CustomerId', TYPES.Int, count);
request.on('row', function (columns) {
console.log('value: ' + columns[0].value);
});
connection.execSql(request);
});
pool.on('error', function (err) {
console.error(err);
});
}
});
The scope of your variables count and firstName are global. By the time the pool.acquire( function get's executed the for loop has completed and it is inserting the last customer twice. One possible solution would be to put an anonymous function inside the for loop e.g. (it doesn't have to be anonymous though)
for (var i = 0; i < customers.length; i++) {
(function(count, firstName) {
...do insert here...
}(i, customers[i].firstname));
}
DEMO
I am unable to retrieve third value of the row it is showing undefined when displayed using alert box .What i am basically trying to achieve is insert 4 rows to table and retrieve them as required sorted based on a column
HTML
<div id="status" name="status">Status Message</div>
Javascript
var db = openDatabase('mydb', '1.0', 'Test DB', 4 * 1024 * 1024);
var msg;
db.transaction(function (tx) {
tx.executeSql('CREATE TABLE IF NOT EXISTS LOGS (id unique, log Text,log1 Text)');
tx.executeSql('INSERT INTO LOGS (id, log,log1) VALUES (1, "foobar","sa")');
tx.executeSql('INSERT INTO LOGS (id, log,log1) VALUES (2, "logmsg","da")');
msg = '<p>Log message created and row inserted.</p>';
document.querySelector('#status').innerHTML = msg;
});
db.transaction(function (tx) {
tx.executeSql('SELECT * FROM LOGS', [], function (tx, results) {
var len = results.rows.length,
i;
msg = "<p>Found rows: " + len + "</p>";
document.querySelector('#status').innerHTML += msg;
for (i = 0; i < len; i++) {
msg = "<p><b>" + results.rows.item(i).log + "</b></p>";
document.querySelector('#status').innerHTML += msg;
var book = results.rows.item(i);
console.log(book);
alert(book.log1);
}
}, null);
});
here i make something very similar to yours, and here it's working. Here my Ids are like:
id integer primary key
So when I do an insert, I don't have to use them, I let web sql take care of it
tx.executeSql('INSERT INTO LOGS (log,log1) VALUES ("logmsg","da")');
Also, I use promises (the code bellow is using angularJs
self.query = function(query, bindings) {
bindings = typeof bindings !== 'undefined' ? bindings : [];
var deferred = $q.defer();
self.db.transaction(function(transaction) {
transaction.executeSql(query, bindings, function(transaction, result) {
deferred.resolve(result);
}, function(transaction, error) {
deferred.reject(error);
});
});
return deferred.promise;
};
self.fetchAll = function(result) {
var output = [];
for (var i = 0; i < result.rows.length; i++) {
output.push(result.rows.item(i));
}
return output;
};
self.fetch = function(result) {
return result.rows.item(0);
};
So I can use it this way:
return DB.query('SELECT * FROM registro WHERE dia = ? and mes = ? and ano = ? order by horario', [dia, mes, ano])
.then(function(result){
return DB.fetchAll(result);
});
I hope this can get you some directions...
Your DEMO link works fine for me (with Chrome 39) - I'm getting 'sa', 'da' alerts after running it. So I think it's something specific to your browser or more probably your cache.
Have you maybe created LOG table without the log1 column at first? Maybe it's still stored in your browser, because
CREATE TABLE IF NOT EXISTS LOGS (id unique, log Text,log1 Text)
line is not going to override it.
In Chrome you can check WebSQL schema hold by the browser with ChromeDevTools and 'Resources' tab, take a look there and see if mydb/LOGS table have your log1 column and data in it.
I am trying to select everything from contracts db and compare the first name of HTML5 textbox with the db entry to alert for duplicates. My first target is to save the result of the query into sql2 variable. ( I cannot do that , please help! ).
db = window.openDatabase("contactDB", "1.0", "Contact Database", 1000000); //name,version,display name, size
addButton.addEventListener(
"click",
function(){
db.transaction(
//function sql statements
function (tx){
ensureTableExists(tx);
var firstName = firstNameBox.value;
var lastName = lastNameBox.value;
var sql = 'INSERT INTO Contacts (firstName, lastName) VALUES ("'+firstName+'","'+lastName+'")';
tx.executeSql(sql);
// Attempting to check for duplicates
var sql2 = 'SELECT * FROM Contacts', WHERE firstName = "'+firstname+'";
tx.executeSql(sql2);
alert(sql2);
},
//error callback
function (err) { alert("error callback "+err.code); },
//success callback
function (err) { //alert("success callback "+err.code);
loadFromDB();
}) // db.trasaction
} // click handler
);
Lookin at this line:
var sql2 = 'SELECT * FROM Contacts', WHERE firstName = "'+firstname+'";
JS variable "firstname" is mistyped (No capital N on Name). This will turn your query into:
'SELECT * FROM Contacts WHERE firstName = "undefined"'
Also, why is there ', before WHERE? I am surprised you did not get an error.
Try rewriting your query like so:
var sql2 = 'SELECT * FROM Contacts WHERE firstName = "'+firstName+'"';