2011-02-07 138 views
0

我在钛手机中使用sqlite。我没有问题在另一张桌子上运行更新,在同一个数据库中,所以我的连接似乎没问题。然而,当我在表上运行插入时,我没有得到任何插入的数据,也没有引发错误/异常。所以我很困惑发生了什么。这里是我的表结构SQL插入没有错误,但表没有数据

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

请!!!!!准备SQL语句时逃脱你的价值观! – Benoit 2011-02-07 17:20:57

回答

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

SQL字符串文字将被单引号包围,而不是双引号。

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

是不正确的说法。

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

是一个正确的SQL语句。

此外,您必须确保您插入的内容已正确转义(您不知道)。因此,在将其与SQL语句的其余部分连接起来之前,您必须将变量内的每个单引号加倍。

+0

感谢您的回复。我基于我的示例关闭本教程http://mobile.tutsplus.com/tutorials/appcelerator/titanium-mobile-database-driven-tables-with-sqlite-part-2/ 我还没有机会通过删除双引号来更改和检查我的代码,但是如果您能告诉我这与他们的代码有什么区别,或者正在做什么,这将有所帮助。我仍然有点新的SQL,所以只是想确保我明白你说的正确。谢谢您的帮助。 – bdizzle 2011-02-07 17:43:38

相关问题