SQLite插入到表中,使用JSON.stringyfy.以带引号的字符串分隔

SQLite insert into table, with JSON.stringyfy. Breaks with Quoted String

本文关键字:分隔 字符串 stringyfy JSON 插入 使用 SQLite      更新时间:2023-09-26

我在手机上使用SQLite,主要用于混合移动应用开发。

我像这样在一列中存储数据。

var QueryToInsert = JSON.stringify(object) // where object is defined as below
INSERT OR REPLACE INTO Table (id,data) VALUES ('1', " ' " + QueryToInsert + " ' " );

变成

INSERT OR REPLACE INTO Table (id,data) VALUES ('1','[{"name":"Romeo","lastName":"Juliet"}]')

虽然可以,但是如果我有一个这样的对象:

var object = {"name": "In connection with this appellative of 'Whalebone Whales' , it is of great..." }  

注意 " 的字符串。

现在如果我做了。

 INSERT OR REPLACE INTO Table (id,data) VALUES ('1', " ' " + JSON.stringify(object) + " ' " );

显示错误:

{"code":5,"message":"near '"Whalebone'": syntax error"}

解决方案我已经尝试过了:

在查询之前用某个字符替换所有的'。它确实工作,但是当有很多数据和很多表时,替换所有的'是一个缓慢的过程。

我正在寻找任何解决方案,将帮助我与这个。

在SQL中,字符串中的单引号必须通过双引号进行转义:

INSERT ... VALUES ('... of ''Whalebone Whales'' ...');

但是,使用参数可以更容易地避免这样的格式化问题:

tx.executeSql("INSERT OR REPLACE INTO Table (id,data) VALUES (?, ?);",
              ['1', JSON.stringify(object)],
              onSuccess, onError);