MySQL NodeJS prepared statement on INSERTING OR UPDATING table name?

Here is the code I am looking to do:

connection.query({
sql: 'CREATE TABLE ? ( `wage` FLOAT NOT NULL , `monday` FLOAT NOT NULL , `tuesday` FLOAT NOT NULL , `wednesday` FLOAT NOT NULL , `thursday` FLOAT NOT NULL , `friday`) ENGINE = InnoDB;',
timeout: 40000, // 40s
},
//[arg1],
function (error, results, fields) {

if (error) {
console.log("Table creation failed");
}else{
console.log("Table creation success");
}

}

);

This does not work as a prepared statement as it takes it and puts it in quotation marks meaning the statement looks like so:

CREATE TABLE 'test' ( `wage` FLOAT NOT NULL , `monday` FLOAT NOT NULL , `tuesday` FLOAT NOT NULL , `wednesday` FLOAT NOT NULL , `thursday` FLOAT NOT NULL , `friday`) ENGINE = InnoDB;

Which is not valid

So instead I am foced to write the statement like this:

connection.query({
sql: 'CREATE TABLE '+arg1+' ( `wage` FLOAT NOT NULL , `monday` FLOAT NOT NULL , `tuesday` FLOAT NOT NULL , `wednesday` FLOAT NOT NULL , `thursday` FLOAT NOT NULL , `friday` FLOAT NOT NULL) ENGINE = InnoDB;',
timeout: 40000, // 40s
},
//[''],
function (error, results, fields) {

if (error) {
console.log("Table creation failed");
}else{
console.log("Table creation success");
}

}

);

This works but it now opens me up to SQL injection which is what I am trying to avoid.

Is there any way I can resolve this and use the prepared statements?

https://www.npmjs.com/package/mysql – This is the package I use

20 thoughts on “MySQL NodeJS prepared statement on INSERTING OR UPDATING table name?”

Leave a Comment