Reputation: 41
I want to dynamically create a Table in MySQL from Node.js
con.query('CREATE TABLE ?', req.params.username + '(id INT(100) NOT NULL
AUTO_INCREMENT, name TINYTEXT, PRIMARY KEY(id))', function (err, result) {
if (err) console.log(err);
else console.log('Table created ' + result);
});
When the query is hard-coded like ,
con.query('CREATE TABLE Sample (id INT(100) NOT NULL AUTO_INCREMENT, name
TINYTEXT, PRIMARY KEY(id))', function (err, result) {
if (err) console.log(err);
else console.log('Table created ' + result);
});
It works.
So, my question is how to create a table dynamically ?
Upvotes: 4
Views: 5726
Reputation: 108676
You're trying to use a parameterized query to substitute a table name. You Can't Do That™. You can't do it with column names either.
You need to write code containing a text string with your data-definition language without ?
parameters and then run it. That's easy to do with string manipulation in JS.
var tableDef = 'CREATE TABLE '+ req.params.username + ' (id INT(100) NOT NULL AUTO_INCREMENT, name TINYTEXT, PRIMARY KEY(id))';
con.query(tableDef, ...etc )
Upvotes: 5