sql insert没有错误,但表没有数据

时间:2011-02-07 17:13:03

标签: javascript sql sqlite appcelerator-mobile

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

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

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

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();

2 个答案:

答案 0 :(得分:1)

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

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

不是正确的陈述。

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

是一个正确的SQL语句。

此外,你必须确保你插入的内容被正确转义(你没有)。因此,在将变量与SQL语句的其余部分连接之前,必须将变量中的每个单引号加倍。

答案 1 :(得分: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);