开发者

Insert into SQLite with variables using javascript

开发者 https://www.devze.com 2022-12-08 15:43 出处:网络
I am developing an extension for Firefox and I have created SQLite DB. When inserting values into the table I get an error message:

I am developing an extension for Firefox and I have created SQLite DB. When inserting values into the table I get an error message:

Error: Permission denied for http://en.wikipedia.org to call method UnnamedClass.toString on <>.

The string valu开发者_开发百科es to be inserted are stored in a variable.

var book = "Harry Potter";
var myInsertQuery = 'INSERT INTO mybooks_tbl(title) VALUES('+ book + ');';

How do we insert data into the table as variables and not as strings?


SQLite follows the ANSI standard for string literals:

A string constant is formed by enclosing the string in single quotes ('). A single quote within the string can be encoded by putting two single quotes in a row

so:

function sqlstr(s) {
    return "'"+s.replace(/'/g, "''")+"'";
}

var query= 'INSERT INTO books(title) VALUES('+sqlstr(book)+');';

You must remember to escape all string literals like this, or you will have made a client-side SQL-injection hole.


There is error in the string only var query= 'INSERT INTO books(title) VALUES('+sqlstr(book)+');';

tx.executeSql('INSERT INTO CLASS_LIST ("class_title","") VALUES("+v.classTitle+")');


For sqlite3:

After some research, I found a simple way to not worry about assembling the string of a query. You've just to add parameters with colon ahead.

let myObj = {
    paramOne: "First value",
    paramTwo: "Second value",
};
let sqlQuery = 'INSERT INTO myTable VALUES(:paramOne, :paramTwo);';

# Run command and variable will be replaces
db.run(sqlQuery, [myObj.paramOne, myObj.paramTwo], ...)
0

精彩评论

暂无评论...
验证码 换一张
取 消