【问题标题】:no error on sql insert, yet table has no datasql插入没有错误,但表没有数据
【发布时间】:2011-06-22 21:24:34
【问题描述】:

我在钛手机中使用 sqlite。我在同一个数据库中的另一个表上运行更新没有问题,所以我的连接似乎没问题。但是,当我在表上运行插入时,我没有插入任何数据,也没有抛出错误/异常。所以我对正在发生的事情感到困惑。这是我的表结构

CREATE TABLE events (
gCal_uid VARCHAR,
title VARCHAR,
content VARCHAR,
location VARCHAR,
startTime VARCHAR, 
endTime VARCHAR, 
published VARCHAR,
updated VARCHAR,
eventStatus VARCHAR
);

这里是代码。你可以看到下面的插入语句。在变量的输出上,它们都有数据。可能是我的语法错误?

var db = Ti.Database.open('content');
Titanium.API.info(" number or results returned = " + cal.feed.entry.length);
var i;
for (i=0; i < cal.feed.entry.length; i++){
    var e = cal.feed.entry[i];

    var calUid = e.gCal$uid.value;
    var title = e.title.$t;
    var content = e.content.$t;
    var location = e.gd$where.valueString;
    var startTime = e.gd$when[0].startTime;
    var endTime =  e.gd$when[0].endTime;
    var published = e.published.$t;
    var updated = e.updated.$t;
    var eventStatus = e.gd$eventStatus.value;

    Titanium.API.info(calUid + title + content + location + startTime + endTime + published + updated + eventStatus);

    var theData = db.execute('INSERT INTO events (gCal_uid, title, content, location, startTime, endTime, published, updated, eventStatus) VALUES("'+calUid+'","'+title+'", "'+content+'", "'+location+'", "'+startTime+'", "'+endTime+'", "'+published+'", "'+updated+'", "'+eventStatus+'")');
    theData;
    Ti.API.info("rows inserted" + i);
}
Ti.API.info("closed the db");
db.close();

【问题讨论】:

  • 请!!!!在准备 SQL 语句时转义值!

标签: javascript sql sqlite appcelerator-mobile


【解决方案1】:

SQL 使用单引号。 Javascript 使用任何一种。

您希望生成的 SQL 就像您编写的一样

INSERT info foo (a,b) values ('a value', 'b value')

最简单更正确的等价物是:

var theData = db.execute("INSERT INTO events (gCal_uid, title, content, location, startTime, endTime, published, updated, eventStatus) VALUES('"+calUid+"','"+title+"','"+content+"','"+location+"','"+startTime+"','"+endTime+"','"+published+"','"+updated+"','"+eventStatus+"')");

但您确实想使用参数替换来避免注入问题和引用错误,例如

var theData = db.execute("INSERT INTO events (gCal_uid, title, content, location, startTime, endTime, published, updated, eventStatus) values (?,?,?,?,?,?,?,?,?)", calUid, title, content, location, startTime, endTime, published, updated, eventStatus);

【讨论】:

    【解决方案2】:

    SQL 字符串文字应该用单引号括起来,而不是双引号。

    INSERT INTO foo (a) VALUES("a");
    

    不是正确的说法。

    INSERT INTO foo (a) VALUES('a');
    

    是正确的 SQL 语句。

    此外,您必须确保您插入的内容被正确转义(您没有)。因此,您必须先将变量中的每个单引号加倍,然后再将其与 SQL 语句的其余部分连接起来。

    【讨论】:

    • 感谢您的回复。我的示例基于本教程mobile.tutsplus.com/tutorials/appcelerator/… 我没有机会通过删除双引号来更改和检查我的代码,但如果你能告诉我这与他们的代码有什么区别,这将有所帮助,或者正在做什么。我对 sql 还是有点陌生​​,所以只是想确保我能正确理解你的意思。感谢您的帮助。
    猜你喜欢
    • 2019-03-16
    • 2011-02-10
    • 1970-01-01
    • 2021-12-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多