I am trying to insert some data with node.js. I installed MySQL support via npm, but It still seems to fail to input the right strings with INSERT INTO. (the row types in the database are tinytext and the strings are smaller then 255 charachters.)
Here is my code https://hastebin.com/komikahatu.http
The expected output is that it inserts the arguments (what is catched by /name) and the username from the user that executes the command (/name).
console.log('Dirname: ' + __dirname);
const bot = require('../core.js');
bot.on("polling_error", (msg) => console.log(msg));
var config = require('../config.json');
var mysql = require('mysql');
var sqlhost = config.sql.host;
var sqluser = config.sql.user;
var sqlpass = config.sql.password;
var sqldb = config.sql.database;
var con = mysql.createConnection({
host: sqlhost,
user: sqluser,
password: sqlpass,
database: sqldb
});
bot.onText(/\/name (.+)/, (msg, match) => {
const chatId = msg.chat.id;
// 'msg' is the received Message from Telegram
// 'match' is the result of executing the regexp above on the text content
// of the message
let username;
const name = match[1].toString(); // the captured name
if(msg.from.username !== ''){
username = msg.from.username;
}
var setnickname = {
username_: username,
nickname_: name
};
var sql = con.query('INSERT INTO nickname_data VALUES (?)', setnickname, function (err, result){
console.log(sql.sql);
if (err) {
console.error(err)
return;
}
console.error(result);
});
if (name !== "undefined") {
bot.sendMessage(chatId, 'Welcome ' + name + '!');
// bot.sendMessage(chatId, 'Welcome ' + msg.from.name + '!');
// config.information.normalusername = name;
}
});
Try this
var setnickname = {
username_: String(username),
nickname_: String(name)
};
var sql = con.query('INSERT INTO nickname_data SET ?', setnickname, function (err, result){
console.log(sql.sql);
if (err) {
console.error(err)
return;
}
console.error(result);
});
You can also pass the second parameter as an array when using VALUES
keyword in the query.something like
var setnickname = [String(username),String(name)];
var sql = con.query('INSERT INTO nickname_data(username_,nickname_) VALUES (?,?)', setnickname, function (err, result){
console.log(sql.sql);
if (err) {
console.error(err)
return;
}
console.error(result);
});