0

I've been searching and trying a lot but can't figure it out. I want to INSERT 8 variables I receive from an API call into an SQLite table. Everything is correctly executed, but when I query the table it shows null for all values.

I receive the for example the following req object:

REQ object:  { id: '22',
type: 'Buy',
userId: '2000',
userName: 'Daniela',
symbol: 'SPY',
shares: '15000',
price: '99.99',
timestamp: '2014-10-10 14:39:25' }

I then assign new variables:

var id = req.query.id;
var tradeType = req.query.tradeType;
var userId = req.query.userId;
var userName = req.query.userName;
var symbol = req.query.symbol;
var shares = req.query.shares;
var price = req.query.price;
var timestamp = req.query.timestamp;

Then I put it together in a sql string:

var sql =
  "INSERT INTO trades (id, tradeType, userId, userName, symbol, shares, price, timestamp) VALUES (?,?,?,?,?,?,?,?)",
id,
tradeType,
userId,
userName,
symbol,
shares,
price,
timestamp;

And lastly, I write it to the table:

var params = [];
db.all(sql, params, (err, rows) => {
if (err) {
  console.log("Error when adding trade: ", err.message);
}
console.log("inserted ", rows);
});

Everything works perfectly when I replace the variables with hardcoded strings or numbers, like this:

var sql =
  "INSERT INTO trades (id, tradeType, userId, userName, symbol, shares, price, timestamp) VALUES (2,'Sell',100,'TestName','AAPL',100,99.99,'2014-10-12 13:20:30')"

I need the sql string to be dynamic as the data comes in from API calls. I read that it might be related to the fact that JavaScript assign object references by references as opposed to by value. I tried to String(variable) everything but didn't work either.

0

1 Answer 1

2

You don't seem to be populating the params[] array anywhere, so you should try doing that:

var sql = "INSERT INTO trades (id, tradeType, userId, userName, symbol, shares, price, timestamp) VALUES (?,?,?,?,?,?,?,?)";
var params = [id, tradeType, userId, userName, symbol, shares, price, timestamp];
db.all(sql, params, (err, rows) => {
    if (err) {
        console.log("Error when adding trade: ", err.message);
    }
    console.log("inserted ", rows);
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.