I'm fairly new to Node.Js and JS in general. I was trying to create a SQL query for a table. After that, I create a separate query to get one/multiple rows from another table that have the same ID (in here LGID) as the row from the first query. Like a JOIN command but I need the results from the second query as a separate object.
I am using the "node-firebird" client.
Everything works, except "the entire code from the second query"
My expected Output would be something like this:
{
"KDNR": "1",
"NUMBER": "+49123456789",
"NAME1": "John",
"NAME2": "Doe,
"STRASSE": "Musterstrasse 38",
"PLZ": "12345",
"ORT": "Musterstadt",
"TEL": "+49123456787",
"TNK": {
{"NAME": "TANK1"},
{"NAME": "TANK2"},
}
}
db.query('SELECT * FROM LG WHERE NAME1 = ?', [req.userData.orga], (err, lgResult) => {
if (err)
throw err;
lgResult.forEach((row) => {
row.KDNR = ab2str(row.KDNR);
row.NUMBER = ab2str(row.NUMBER);
row.NAME1 = ab2str(row.NAME1);
row.NAME2 = ab2str(row.NAME2);
row.STRASSE = ab2str(row.STRASSE);
row.PLZ = ab2str(row.PLZ);
row.ORT = ab2str(row.ORT);
row.TEL = ab2str(row.TEL);
console.log('test');
db.query('SELECT * FROM TNK WHERE LGID = ?', [1], (errN, tnkResult) => {
if (errN)
return res.status(500).json({ error: 'Error queryisssng DB' });
console.log('another test');
row.TNK.push(tnkResult);
});
return res.status(200).json(lgResult);
});
I can see the test multiple times in the console, but not the another test.
I hope this is enough code for you to help.
Related
The Issiue
Issue is basically if i try to combine query+variable or put it in "fake pdo" style, it does not work.
Code
if(page == "profile"){
var user = "Failed to load.";
con.query('SELECT * FROM users WHERE id = '+con.escape(parseInt(userIDRequested)), function (err, result, fields) {
//console.log(result);
user= result[0].nick;
io.emit('userinfo', { nick: user});
});
}
app.get("/user/:start", function(req, res){
page = "profile";
var user_id = req.params['start'];
pageid = user_id;
if(didshitgetupdated == false){
useridRequested = pageid;
didshitgetupdated = true;
}
res.writeHeader(200, {"Content-Type": "text/html"});
let btlib = btNetLib(res);
btlib.btSend(navbar);
btlib.btSendFile("profile/index.html");
finishConnection(res);
})
but for some reason i get this:
TypeError: Cannot read property 'nick' of undefined
at Query.<anonymous> (D:\bricktalenode\bricktale.js:36:29)
at Query.<anonymous> (D:\bricktalenode\node_modules\mysql\lib\Connection.js:526:10)
at Query._callback (D:\bricktalenode\node_modules\mysql\lib\Connection.js:488:16)
at Query.Sequence.end (D:\bricktalenode\node_modules\mysql\lib\protocol\sequences\Sequence.js:83:24)
at Query._handleFinalResultPacket (D:\bricktalenode\node_modules\mysql\lib\protocol\sequences\Query.js:149:8)
at Query.EofPacket (D:\bricktalenode\node_modules\mysql\lib\protocol\sequences\Query.js:133:8)
at Protocol._parsePacket (D:\bricktalenode\node_modules\mysql\lib\protocol\Protocol.js:291:23)
at Parser._parsePacket (D:\bricktalenode\node_modules\mysql\lib\protocol\Parser.js:433:10)
at Parser.write (D:\bricktalenode\node_modules\mysql\lib\protocol\Parser.js:43:10)
at Protocol.write (D:\bricktalenode\node_modules\mysql\lib\protocol\Protocol.js:38:16)
Things i tried
making a if condition to check it
(did not helped)
connecting database using another thing
i used same query(changed variable for php though) in php to access, query is ok, so issue on my node.js code then.
waiting for some time ( did not helped)
parse int
nothing really helped that i done
but for some reason i get stuff correctly using console.log(result);
but i cant fetch them using the code.
The results
[ RowDataPacket {
nick: '[MODERATED 5]',
id: 5,
password: 'fdaf40dc5531c0acf82911892f552f0a',
banned: 0,
coins: 0,
registerdate: 2021-05-10T02:55:45.000Z,
status: 'BETA STATUS',
rank: 'Player',
rep: 1,
token: 'token',
lastonline: '2021-05-10 03:05:08',
lastdaily: 2021-05-19T07:04:34.000Z } ]
but i cannot access it
app.get("/user", function(req, res){
page = "profile";
res.writeHeader(200, {"Content-Type": "text/html"});
let btlib = btNetLib(res);
btlib.btSend(navbar);
btlib.btSendFile("profile/index.html");
var sql = 'SELECT * FROM users WHERE id = ?';
con.query(sql, req.query.id, function (err, result) {
if (err) throw err;
setInterval(() => {
var bricklet;
bricklet = result[0].nick;
console.log(bricklet);
io.emit('userinfo', { nick: bricklet});
},150);
});
finishConnection(res);
})
moving stuff inside of my app.get solved it.
I currently have a database of people with each individual person and they hold a status value. I am trying to change their status value.
const id = parseInt(req.params.id , 10);
const { valid, messageObj } = validateId(id);
if (!valid) {
res.status(400).send(messageObj);
}
let { status, priority } = req.body;
let people = db.prepare('select * from people').all();
const person = people.find(person => person.id === id);
if(status !== 'none' & status == 'ready' || status == 'done'){
let updates = db.query(
'UPDATE people SET ? WHERE ?',
[{ status: status }, { id: id }]
);
}
I keep getting an error of db.query is not a function but I get that for every function that I try.
Pretty new to SQL but just trying to figure this out or any documentation that will help me as the better-sqlite3 doesn't have any update functions in the official documentation.
I cannot find a function called query() in the better-sqlite3 API for the Database class. I think that you would need to prepare() a Statement object, then run() it.
Also, column names cannot be passed as bound parameters. Your query should look like:
UPDATE people SET status = ? WHERE name = ?
You would need to change this:
let updates =
db.query('UPDATE people SET ? WHERE ?', [{ status: status }, { id: id }]);
To:
const stmt = db.prepare('UPDATE people SET status = ? WHERE id = ?');
const updates = stmt.run(status, id);
According to templates you can use javascript syntax to replace variables to its value.
let updates = db.exec(`UPDATE people SET status='${status}' WHERE id='${id}'`);
I got lets say 100.000 records in array:
var eData = { "id": "1001", "type": "Regular" },
{ "id": "1002", "type": "Chocolate" },
{ "id": "1003", "type": "Blueberry" },
{ "id": "1004", "type": "Devil's Food" }
And so on...
When I fire the node.js script below
var db = require('/QOpenSys/QIBM/ProdData/OPS/Node6/os400/db2i/lib/db2a');
var DBname = "*LOCAL";
var dbconn = new db.dbconn();
dbconn.conn(DBname);
var sqlA = new db.dbstmt(dbconn);
eData.forEach(function(eRow, i) {
var sql = "INSERT INTO lib.table VALUES( xx x x x) WITH NONE"
sqlA.exec(sql, function(rs, err) {
console.log("Execute Done.");
console.log(err);
});
});
The data will be mixed up in DB. Same id and type will be there 10 times, but it will hit the exact number of insertet records.
If I change to execSync, everything turns out right, but seams a bit slow. What am I missing to do async inserts?
What is the fastest way doing huge inserts?
There will be a optimal number of async operations to have processing at any one time. The easiest way to limit the number of async operations is with the excellent async.js module.
https://caolan.github.io/async/docs.html#eachLimit
var async = require('async')
var db = require('/QOpenSys/QIBM/ProdData/OPS/Node6/os400/db2i/lib/db2a');
var DBname = "*LOCAL";
var dbconn = new db.dbconn();
dbconn.conn(DBname);
var sqlA = new db.dbstmt(dbconn);
async.eachLimit(eData, 100, function(eRow, cb) {
var sql = "INSERT INTO lib.table VALUES( xx x x x) WITH NONE"
sqlA.exec(sql, function(rs, err) {
console.log("Execute Done.");
cb(err)
});
}, function (error) {
if (error) {
console.error(error)
} else {
console.log('Done')
}
})
I want to connect to Azure SQL Database using node.js. I found a documentation in MSDN blog and see I directly use their source code to connect. I have entered the correct credentials and successfully connected to the database.
However, when I execute the query, it says invalid object name, my table is dbo.Users. What is the problem?
var Connection = require('tedious').Connection;
var config = {
userName: 'myusername',
password: 'mypw',
server: 'myserver',
// When you connect to Azure SQL Database, you need these next options.
options: { encrypt: true, database: 'mydb' }
};
var connection = new Connection(config);
connection.on('connect', function (err) {
// If no error, then good to proceed.
console.log("Connected");
executeStatement();
});
var Request = require('tedious').Request;
var TYPES = require('tedious').TYPES;
function executeStatement() {
request = new Request("SELECT * FROM dbo.Users;", function (err) {
if (err) {
console.log(err);
}
});
var result = "";
request.on('row', function (columns) {
columns.forEach(function (column) {
if (column.value === null) {
console.log('NULL');
} else {
result += column.value + " ";
}
});
console.log(result);
result = "";
});
request.on('done', function (rowCount, more) {
console.log(rowCount + ' rows returned');
});
connection.execSql(request);
}
According to your comment, as your original question, you just mistaken the table name as
I have checked my database information. I found that my table name is "Table" instead of "Users", and the schema is dbo.
And now you are facing issue:
"Incorrect syntax near the keyword Table".
As the Table is a keyword in MSSQL, you can find it in https://msdn.microsoft.com/en-us/library/ms189822.aspx. In SQL sentence, we will use [] to contain the table name if the table name has a conflict with any keyword.
Try to use SELECT top 1 * FROM [Table]. Furthermore, it is better to rename the table named Table to resolve the conflicts.
Hi I have a question to the azure mobile Service custom API script.
I have a custom script to create a JSON Response.
First step was to get flat objects.
Thsi is my code:
var sql = "SELECT [Project].[id] AS [ID]," +
"[Project].[Name] AS [Name]," +
"FROM [Project]";
request.service.mssql.query(sql, [], {
success: function(results) {
if (results.length === 0) {
response.json(statusCodes.OK, results);
return;
}
var resultSet = [];
results.forEach(function(poi) {
resultSet.push(
{
ID: poi.ID,
Name: poi.Name,
RelatedObjects:
{
[
**???**
]
},
});
})
response.json(statusCodes.OK, resultSet);
}
});
This works very well. Now I want to extend my result objects by some sub objects from a releated table. But not simple singel sub properties (this is easy via join), I want to add collections of sub properties selected from another table.
But I don't know how to get the second query into my code? :(
I think it has to be on "???" marked position.
I want to use this JSON self creating code because my result sets are much more complex as the example shows.
Please help!
Ok I solve it with this messi code...
I'm sure there is a more elegant way to do this but I don't found it yet.
var sql = "SELECT [Project].[ID]" +
",[Project].[Name]" +
"FROM [Project]";
var sql2 = "SELECT [ID]" +
",[UniqueSN]" +
",[Name]" +
"FROM [DataLogger]" +
"WHERE [DataLogger].[ProjectID] = ?";
request.service.mssql.query(sql, [id], {
success: function(results) {
var resultSet = [];
results.forEach(function(poi) {
var loggerResultSet = [];
request.service.mssql.query(sql2, [poi.ID], {
success: function(results2) {
results2.forEach(function(logger) {
loggerResultSet.push(
{
ID: logger.ID,
Name: logger.Name,
UniqueSN: logger.UniqueSN,
});
})
resultSet.push(
{
ID: poi.ID,
Name: poi.Name,
Logger: loggerResultSet,
});
response.json(statusCodes.OK, resultSet);
console.log(JSON.stringify(resultSet));
}
});
})
}
});