async function get_info(compName) {
let company = {
name:""
, activityNumber:""
, siret :""
, adresse :""
, tva :""
, logo:0
};
buff = await db.all("SELECT * FROM company WHERE name = ?", [compName], (err, rows) => {
if (err) {
console.log(err)
return err;
}
rows.forEach(element => {
console.log(element.name) // WORK
company.name = element.name;
company.activityNumber = element.activityNumber;
company.adresse = element.adresse;
company.logo = element.logo;
company.siret = element.siret;
company.tva = element.tva;
});
});
console.log(" ... " + company.name) // DOSENT WORK
return company;
}
I'm trying to get company fill and get data out of my database.
The first console.log() is good but not the second one, it's empty, and the object it returns have defaults values, there will be only one element who will match "WHERE name = ?" so I don't worry about erasing the value.
When an existing SQL record exists I want to use it rather than adding another, but if it doesn't yet exist I want to add it. The issue I am having is that when my Node.js app's endpoint is called it's not executing in the correct order so the SQL lookup to find existing records is happening after I check it's length to see if I need to add a new record.
// it does this second
let existingGet = "SELECT * FROM Items WHERE name = '" + productName + "'";
let existingItem = async () => {
db.query(existingGet, function (err, rows, fields) {
return rows;
});
};
// it does this first
if (await existingItem().length > 0) {
// Existing found, use existing
itemId = existingItem.ID;
} else {
// Item not found, create new
var sql = "INSERT INTO Items (...) VALUES (...)";
await db.query(sql, async function (err, result) {
itemId = existingItem.affectedRows.ID;
});
}
The desired outcome is that it does the first section before the second section because the second section needs the results of the first.
Try removing the outer brackets so that the existingItem will receive the result from the query
// it does this second
let existingGet = "SELECT * FROM Items WHERE name = '" + productName + "'";
//removed outer brackets
let existingItem = async () =>
db.query(existingGet, function (err, rows, fields) {
return rows;
});
// it does this first
if (await existingItem().length > 0) {
// Existing found, use existing
itemId = existingItem.ID;
} else {
// Item not found, create new
var sql = "INSERT INTO Items (...) VALUES (...)";
await db.query(sql, async function (err, result) {
itemId = existingItem.affectedRows.ID;
});
}
Do it in a single db call using sql command
"INSERT INTO Items (...) VALUES (...)
WHERE NOT EXISTS (SELECT 1 FROM Items WHERE name = ...)"
And use sql command parameters instead of concatenation to avoid sql injection.
First off, I apologize if the title isn't accurate but I'm struggling to find the words to accurately describe my problem.
I'm working on a project where I'm trying to record Twitter information that I have compiled from a scraper and is currently in CSV format.
I convert that information into JSON using csvtojson, but I'm running into a problem.
Each word in the tweet I'm trying to separate by itself and then apply the rest of the information from that specific row in the CSV to that specific word.
Here's an example of a "successful" outcome:
I'm just not sure how to split up the array I've created where I can apply each word as a new row to the array. I'm assuming I need to separate out how I'm inserting the data, but I'm not sure how to do that?
const fileName = "items.csv";
csvtojson().fromFile(fileName).then(source => {
// Console log initial CSV data
// console.log(source);
for (var i = 0; i < source.length; i++) {
var tweets__contentText = source[i]["tweets__contentText"],
tweets__conversationId = source[i]["tweets__conversationId"],
tweets__replies = source[i][" tweets__replies"],
tweets__retweets = source[i]["tweets__retweets"],
tweets__favorites = source[i]["tweets__favorites"],
tweets__dateTime = source[i]["tweets__dateTime"],
tweets__tweetId = source[i]["tweets__tweetId"]
var tweets__modified = tweets__contentText.match(/\b(\w+)\b/g);
console.log(tweets__modified);
var insertStatement = `INSERT INTO ctdata values(?, ?, ?, ?, ?, ?, ?, ?)`;
var items = [tweets__modified, tweets__contentText, tweets__conversationId, tweets__replies, tweets__retweets, tweets__favorites, tweets__dateTime, tweets__tweetId];
// Insert data of current row into database
db.query(insertStatement, items, (err, results, fields) => {
if (err) {
console.log("Unable to insert item at row ", i + 1);
return console.log(err);
}
});
}
console.log("All items stored into database successfully!");
});
To insert multiple records, the SQL format is something like:
INSERT INTO table_name (column_name_1, column_name_2, column_name_3)
VALUES
(?, ?, ?),
(?, ?, ?),
(?, ?, ?)
...
;
So we need to construct the query in above format, according to which I have re-written a part of your code with the changes
var tweets__modified = tweets__contentText.match(/\b(\w+)\b/g);
console.log(tweets__modified);
// creating a string for numbers of records we want to create
var sql_insert_statement = tweets__modified.map((record) => '(?, ?, ?, ?, ?, ?, ?, ?)').join(', ');
// appending the above string to create a final SQL query
var insertStatement = `INSERT INTO ctdata ("tweets__singleWord", "tweets__contentText", "tweets__conversationId", "tweets__replies", "tweets__retweets", "tweets__favorites", "tweets__dateTime", "tweets__tweetId") values ${sql_insert_statement}`;
// creating a SQL query data in which
// we have all the columns data for a record
// times the number of recrods
var insertStatementItems = tweets__modified.reduce((acc, record) => {
acc = [...acc, record, tweets__contentText, tweets__conversationId, tweets__replies, tweets__retweets, tweets__favorites, tweets__dateTime, tweets__tweetId];
return acc; // was missing
}, []);
console.log({ insertStatement, insertStatementItems });
// Insert data of current row into database
db.query(insertStatement, insertStatementItems, (err, results, fields) => {
if (err) {
console.log("Unable to insert item at row ", i + 1);
return console.log(err);
}
});
Note: But mind you, there is another issue with your code, If you are expecting for this line console.log("All items stored into database successfully!"); to be printed after all the insert operation, that is wrong. Since it's async code, this line will be printed first before any operation is executed. I have added two pieces of code to fix that.
If your environment support async/await, then this code might help you
const fileName = "items.csv";
csvtojson().fromFile(fileName)
.then(async (source) => {
// Console log initial CSV data
// console.log(source);
db_insert_promises = []
for (var i = 0; i < source.length; i++) {
var tweets__contentText = source[i]["tweets__contentText"],
tweets__conversationId = source[i]["tweets__conversationId"],
tweets__replies = source[i][" tweets__replies"],
tweets__retweets = source[i]["tweets__retweets"],
tweets__favorites = source[i]["tweets__favorites"],
tweets__dateTime = source[i]["tweets__dateTime"],
tweets__tweetId = source[i]["tweets__tweetId"]
var tweets__modified = tweets__contentText.match(/\b(\w+)\b/g);
console.log(tweets__modified);
var sql_insert_statement = tweets__modified.map((record) => '(?, ?, ?, ?, ?, ?, ?, ?)').join(', ');
var insertStatement = `INSERT INTO ctdata values ${sql_insert_statement}`;
var insertStatementItems = tweets__modified.reduce((acc, record) => {
acc = [...acc, record, tweets__contentText, tweets__conversationId, tweets__replies, tweets__retweets, tweets__favorites, tweets__dateTime, tweets__tweetId];
return acc; // was missing
}, []);
// Insert data of current row into database
db_insert_promise_for_tweet = await new Promise(function(resolve, reject) {
db.query(insertStatement, insertStatementItems, (err, results, fields) => {
if (err) return reject(err);
return resolve(results, fields);
});
});
}
console.log("All items stored into database successfully!");
})
.catch(console.error);
If your environment doesn't support async/await, then this code might help you
const fileName = "items.csv";
csvtojson().fromFile(fileName)
.then(source => {
// Console log initial CSV data
// console.log(source);
db_insert_promises = []
for (var i = 0; i < source.length; i++) {
var tweets__contentText = source[i]["tweets__contentText"],
tweets__conversationId = source[i]["tweets__conversationId"],
tweets__replies = source[i][" tweets__replies"],
tweets__retweets = source[i]["tweets__retweets"],
tweets__favorites = source[i]["tweets__favorites"],
tweets__dateTime = source[i]["tweets__dateTime"],
tweets__tweetId = source[i]["tweets__tweetId"]
var tweets__modified = tweets__contentText.match(/\b(\w+)\b/g);
console.log(tweets__modified);
var sql_insert_statement = tweets__modified.map((record) => '(?, ?, ?, ?, ?, ?, ?, ?)').join(', ');
var insertStatement = `INSERT INTO ctdata values ${sql_insert_statement}`;
var insertStatementItems = tweets__modified.reduce((acc, record) => {
acc = [...acc, record, tweets__contentText, tweets__conversationId, tweets__replies, tweets__retweets, tweets__favorites, tweets__dateTime, tweets__tweetId];
return acc; // was missing
}, []);
// Insert data of current row into database
db_insert_promise_for_tweet = new Promise(function(resolve, reject) {
db.query(insertStatement, insertStatementItems, (err, results, fields) => {
if (err) return reject(err);
return resolve(results, fields);
});
});
db_insert_promises.push(db_insert_promise_for_tweet);
}
return Promise.all(db_insert_promises);
})
.then((result_of_all_insert_query) => {
console.log({ result_of_all_insert_query });
console.log("All items stored into database successfully!");
})
.catch(console.error);
I am making a Discord Bot add a database entry when a new user joins. To avoid duplicate entries I'm checking if the database row ID already has the members ID in it. My problem is if the member is not in the database it comes back as undefined.
var userID = member.id.toString();
var UserName = member.user.username.toString();
// var NickName = member.nickname.toString();
var DateJoined = new Date();
con.query("SELECT ID FROM listAllUsers", function (err, selectResult, fields) {
var filter = selectResult.filter(m => m.ID === userID);
console.log(filter[0].ID)
if(filter[0].ID == userID) {
console.log(`That user all ready exists in the database.`)
} else {
var sql = `INSERT INTO listAllUsers (ID, UserName, NickName, DateJoined) VALUES ('${ID}', '${UserName}', 'none', '${DateJoined}')`;
con.query(sql, function (err, result) {
if (err) throw err;
console.log(`User: ${UserName} -- ${ID} has joined the server. Added to the Database`);
});
}
});
var filter = selectResult.filter(m => m.ID === userID);
This checks if the ID is equal to any of the ID's in the database. But this is also my problem. Because if this comes back empty it will make this:
console.log(filter[0].ID) undefined. Well actually the .ID bit comes back undefined.
Well if you have an entry, than you already know the id exists....
if (filter.length > 0) {
// you have a user with the id
}
But wouldn't it make more sense to just query the user id instead of returning everyone? SELECT ID FROM listAllUsers WHERE ID=userID
sql.get(`SELECT * FROM scores ORDER BY points DESC`).then(allScores => {
console.log(allScores);
});
This should give me all of the rows ordered by points, but I'm only getting the first row.
How do I access all of the other rows using javascript?
Use sql.all instead of sql.get refer http://www.sqlitetutorial.net/sqlite-nodejs/query/
Define your db instance as follows:
const sqlite3 = require('sqlite3').verbose();
// open the database
let db = new sqlite3.Database('./db/yourCoolDB');
And then,
let sql = `SELECT * FROM scores ORDER BY points DESC`;
db.all(sql, [], (err, rows) => {
if (err) {
throw err;
}
rows.forEach((row) => {
console.log(row.Id); // You can use row.yourAnotherAttributeName
});
});