2011-02-07 139 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

相關問題