简体   繁体   中英

SQLite inserts variable values as Null in Javascript Node.JS

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.

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);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM