Currently this is my code, which inserts the new_item correctly
var new_item = {id_user: id, id_restaurant: id_rest, type: 3, date: date};
connection.query("INSERT INTO table SET ?", [new_item], function(err, results) {
if(err){
...
}
...
}
But now I don't want to send the date with it, I want to use SET ? and do something likedate = NOW() basically I want to insert this:
var new_item = {id_user: id, id_restaurant: id_rest, type: 3};
and use date = NOW()-INTERVAL 6 hour to assign the date.
EDIT: I posted I only wanted Now() but actually I want to set Interval it before inserting.
I think it is better to use moment.js.
You can use Date.now which returns current timestamp(milliseconds), so make sure to format it. The code is as follows:
var a = moment(Date.now()).format('YYYY-MM-DD HH:mm:ss');
Please let me know if this works out
new Date().toISOString().slice(0,10) + " " + new Date().toISOString().slice(11, 19)
same as 'YYYY-MM-DD HH:mm:ss'
Using NOW() is executed by the database interpreter and sets the database time.
You could create a new variable to use in your SQL statement and set the wanted content to that one.
var new_item1 = {id_user: id, id_restaurant: id_rest, type: 3, date: date};
var new_item2 = {id_user: new_item1.id_user, ...};
connection.query("INSERT INTO table SET ?", [new_item2], function(err, results) {
if(err){
...
}
...
}
Then you could configure your column to set the NOW() timestamp as default.
Related
var epochtime = "1610950344";
var datevar = new Date(epochtime *1000);
var mytime = datevar.toISOString().slice(0, 19).replace('T', ' ');
console.log("DATEEEEEEEEEE : "+mytime);
const query = `INSERT INTO MYTIME (MY_TIME, NAME) VALUES ('${mytime}', 'ANN')`;
updateDB(query); //Custom function to create a connection and insert the data into the table
MY_TIME is defined as TIMESTAMP in mysql schema. The above query is working except for the MY_TIME field. When mytime gets inserted, it changes the values to "0000-00-00 00:00:00" in mysql. Why is this happening? Is there anything wrong with the data conversion. Please help
You can simply query like this:
INSERT INTO MYTIME (MY_TIME, NAME) VALUES (FROM_UNIXTIME(${epochtime}), 'ANN')
i'm trying to create a stats bot for discord but i am having some issues trying to get part of it to work.
What i am trying to do is record the number of messages sent per channel at 5 min intervals. In my bot i have the following code:
// on message events
bot.on("message", async message => {
if(message.author.bot) return;
if(message.channel.type === "dm") return;
//update channel stats
connection.query(`SELECT * FROM channel_stats WHERE channel_id = '${message.channel.id}' AND date BETWEEN timestamp(DATE_SUB(NOW(), INTERVAL 5 MINUTE)) AND timestamp(NOW())`, (err, rows) => {
if(err) throw err;
let sql;
if(rows.length < 1) {
sql = `INSERT INTO channel_stats (channel_id, date, channel_name, channel_message_count) VALUES ('${message.channel.id}', NOW(), '${message.channel.name}', 1)`;
} else {
let channel_message_count = rows[0].channel_message_count;
sql = `UPDATE channel_stats SET channel_message_count = ${channel_message_count + 1}, channel_name = '${message.channel.name}' WHERE channel_id = '${message.channel.id}'`;
};
connection.query(sql)
});
however, the bot always inserts a new row and never updates an existing one.
I ran the sql query SELECT * FROM channel_stats WHERE channel_id = 'xxxxxxxxxxxxx' AND date BETWEEN timestamp(DATE_SUB(NOW(), INTERVAL 5 MINUTE)) AND timestamp(NOW()) manually via phpmyadmin and this seems to be working correctly - only returns rows created within the last 5 mins.
I'm struggling to understand why the bot is constantly adding new rows. Any help would be appreciated.
Thanks!
managed to resolve this myself, had the channel_id row as int(11) which was causing the channel_id to be truncated.
changed it to VARCHAR(30) and it's working perfectly now.
cnx.request("
INSERT INTO
sensorinput
(node_id, temperature, humidity, dateAdded)
VALUES
(1, 2200, 7800, '1998-12-12 23:12:59')");
var date = cnx.request("
SELECT dateAdded
FROM
sensorinput
WHERE id=1
");
Lib.println(date.getResult(0));
Works just fine. Prints the '1998-12-12 23:12:59' from MySQL database without any problems. However if I try to print all timestamps like this:
var date = cnx.request("SELECT dateAdded FROM sensorinput");
for(r in date)
{
Lib.println(date.getResult(0));
}
It will just print ' null '.
Any ideas how to print all the timestamps from sensorinput?
Try This:
var date = cnx.request("SELECT dateAdded FROM sensorinput");
for(r in date)
{
Lib.println(r.dateAdded);
}
With a conditional Insert, I want to know if a row was inserted or if overlap was found.
I have a query that inserts a request into the database if it doesn't overlap with any existing entry. The query works, but how do I know if there's been an collision? The query just executes successfully. Here is my query:
INSERT INTO requests(id, start_time, end_time)
SELECT NULL, 1463631640671,1463636731000,
FROM Dual
WHERE NOT EXISTS (
SELECT * FROM requests
WHERE
start_time < 1463638531000 AND
end_time > 1463636731000
)
For your information. I'm doing this inside Node.js with the mysql package.
and the code looks like this, and it returns 'SUCCESS' every time.
var queryString = "INSERT INTO requests(id, start_time, end_time..."
connection.query(queryString, function(error, results, fields) {
if (!error) {
console.log('SUCCESS!');
}
else {
console.log('Insert into requests unsuccessful.');
console.log('ERROR: ' + error);
}
});
you can inspect results.insertId and see if you have something in it.
I have 2 arrays :
columns = ['column1', 'column2'];
data = ['data1', 'data2'];
I'd like to update the table using a prepared query:
conn.query('UPDATE table SET ?? = ? WHERE id = ?', [columns, data, id],
function(err, info){
Excepted sql query :
UPDATE table SET column1 = 'data1', column2 = 'data2' WHERE id = 10
But I get something that looks like :
UPDATE table SET 'column1', 'column2' = 'data1', 'data2' WHERE id = 10
This feature works well for select or insert but it seems not working for update queries. Any thoughts on how I can get this work ?
From node-mysql docs, about escaping query values, we have this:
Arrays are turned into list, e.g. ['a', 'b'] turns into 'a', 'b'
, so it won't work the way you expect.
But, in the docs we also have this:
Objects are turned into key = 'val' pairs. Nested objects are cast to strings.
with an example:
var post = {id: 1, title: 'Hello MySQL'};
var query = connection.query('INSERT INTO posts SET ?', post, function(err, result) {
// Neat!
});
console.log(query.sql); // INSERT INTO posts SET `id` = 1, `title` = 'Hello MySQL'
So, in order to do what you want, the best option IMO, is to convert your arrays into an object like:
{
column1: 'data1',
column2: 'data2'
}
Just to clarify, since after Googling for ages I didn't find an exact example to show what I was looking for. Here is the code which hopefully is what Bobby Shark found out, since I don't think 'SET ??' works.
To UPDATE multiple columns (but not necessarily all) for one row, without typing up every column in the query, but passing an object of {column_name1: 'new_foo', column_name2: 'new_bar', column_name2: 'new_baz'}
(using body-parser to get object of form data)
var blog = req.body.blog; // object as described above
var sql = "UPDATE blog SET ? WHERE id = ?";
connection.query(sql, [blog, req.params.id], function(err, updatedBlog){
if(err){
console.log(err);
} else {
res.redirect("/blogs/" + req.params.id);
}
});
This post by Bala Clark helped (though we've read it in the docs 10 times!). Hope this helps to see example code of object with multiple column updates (name/value pairs). Again found no specific examples in many sites.