Created
December 8, 2011 03:34
-
-
Save karmadude/1445992 to your computer and use it in GitHub Desktop.
Using Node to export MySQL query results to a file as JSON
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// https://github.com/felixge/node-mysql | |
// npm install mysql | |
var mysql = require('mysql'); | |
// http://nodejs.org/docs/v0.6.5/api/fs.html#fs.writeFile | |
var fs = require('fs'); | |
var client = mysql.createClient({ | |
user: 'root', | |
password: 'mysqlpassword' | |
}); | |
client.query('select * from db.table;', function(err, results, fields) { | |
if(err) throw err; | |
fs.writeFile('table.json', JSON.stringify(results), function (err) { | |
if (err) throw err; | |
console.log('Saved!'); | |
}); | |
client.end(); | |
}); |
Please how to log the sql query with parameter $1 $2 .... like this :
client.query(
"INSERT into mytable (id,title,name) VALUES(nextval('id_seq'),$1, $2) RETURNING id",
[req.title, req.name],
function (err, result) {
if (err) {
console.log(err);
} else {
console.log('row inserted in annales with id: ' + result.rows[0].id);
}
writeData('/api/createannales', ?? ?? ? );
client.end();
return res.json(result.rows[0].id);
});
How can I export resultset?
var con = mysql.createConnection({
host: "localhost",
user: "root",
password: "password",
database: "staging"
});
con.connect(function(err) {
if (err) throw err;
console.log("Connected!");
var sql = "SELECT * FROM products";
con.query(sql, function (err, result) {
if (err) throw err;
res.end(JSON.stringify(result));
});
});
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The mysql library has changed a bit.