Shorten Dynamic SQL Query For Loop
I have a function that builds an sql query and then inserts it into the client-side light sql.
I think im using to many for loops, how would i make this shorter?
function insert(dataBase,table,row){
var j = 0;
var sqlQueryArray = [];
sqlQueryArray[j++] = 'INSERT INTO ';
sqlQueryArray[j++] = table
sqlQueryArray[j++] = ' ('
for (var i = row.length - 2; i >= 0; i--){
sqlQueryArray[j++] = row[i].id + ',';
};
sqlQueryArray[j++] = row[(row.length - 1)].id + '';
sqlQueryArray[j++] = ')'
var sqlQueryString = ' VALUES ';
for (var i = row开发者_如何学运维.length - 2; i >= 0; i--){
sqlQueryArray[j++] = '?, ';
};
sqlQueryArray[j++] = '?';
sqlQueryArray[j++] = ');'
for (var i = 0; i < sqlQueryArray.length; i++){
sqlQueryString += sqlQueryArray[i];
}
var rowArray = []
for (var i = row.length - 1; i >= 0; i--){
rowArray[i] = row[i].val;
};
dataBase.openDatabase.transaction(
function (transaction) {
transaction.executeSql(sqlQueryString,
rowArray,
dataBase.nullSQLHandler, dataBase.QueryError);
}
);
}
Assuming you're using a relatively recent browser, you could do something like this:
var insertStatement =
'INSERT INTO ' + table +
' (' + rows.map(function (row) { return row.id; }).join(', ') + ')' +
' VALUES (' + rows.map(function () { return '?'; }).join(', ') + ')';
Whether you should or not is left as an exercise for the reader :)
Edit: I just noticed in a comment to another answer that you are sending this to the server for execution. You should definitely not do that, since a user could easily submit their own SQL and wreak all kinds of havoc on your database. You shouldn't trust any data received over the network.
Whenver Dynamic SQL is created in an application, things are unleashed and children are eaten.
You should really use a parameterized SP for this one for a multitude of security and performance reasons (not to mention readability/maintainability).
First of all, I think you'd be better not tracking the index manually (j++
). Use sqlQueryArray.push() to insert the elements at the end of sqlQueryArray
.
Then, to simplify your code, you can create a function that returns you a custom SQL passing your row
variable as a parameter, with that you can generate the INSERT INTO
clause with all the ?
markers.
精彩评论