let sql = `INSERT INTO user
(name, createAt, updateAt)
VALUES
(:name, :createAt, :updateAt)
`;
let param = `{
"name": "",
"createAt":"",
"updateAt":"",
}`;
const queryFormat = function (query, values) {
if (!values) return query;
query = query.replace(/:(\w+)/g, function (txt, key) {
if (values.hasOwnProperty(key)) {
const v = values[key];
if (typeof v === 'number') {
return v;
} else {
return '"' + this.escape(v) + '"';
}
}
return txt;
}.bind(this));
// log.info('[mysql query]', query);
return query;
};
process.argv.forEach((val, index) => {
console.log(`${index}: ${val}`);
if (index === 2) {
sql = val;
}
if (index === 3) {
param = JSON.parse(val);
}
});
if (param) {
sql = queryFormat(sql, JSON.parse(param));
param = undefined;
}
const mysql = require('mysql');
console.log(sql);
var connection = mysql.createConnection({
host: 'url',
port: 3306,
user: 'username',
password: 'password',
database: 'database',
dateStrings: true
});
connection.connect();
connection.query(sql, function (error, results) {
if (error) throw error;
console.log('The solution is: ', results);
});
connection.end();