2016-10-01 101 views
0

我使用Ionic2與SQLite的,我有以下幾點:SQLite的錯誤:沒有這樣的列:

app.ts

private createDatabase(): void { 
    let db: SQLite = new SQLite(); 
    db.openDatabase({ 
     name: "data.db", 
     location: "default" 
    }).then(() => { 
     db.executeSql("CREATE TABLE IF NOT EXISTS chats (_id TEXT PRIMARY KEY, memberIds TEXT, title TEXT, subTitle TEXT, picture TEXT, lastMessageId TEXT, lastMessageCreatedAt DATE)", {}).then((chatData) => { 
     console.log("chats TABLE CREATED: ", chatData); 
     db.executeSql("CREATE TABLE IF NOT EXISTS messages (_id TEXT PRIMARY KEY, chatId TEXT, senderId TEXT, ownership TEXT, content TEXT, createdAt DATE, changeDate BOOLEAN, readByReceiver BOOLEAN)", {}).then((messageData) => { 
      console.log("messages TABLE CREATED: ", messageData); 
     }, (error) => { 
      console.error("Unable to execute messages sql", error); 
     }); 

     }, (error) => { 
     console.error("Unable to execute chats sql", error); 
     }); 
    }, (error) => { 
     console.error("Unable to open database", error); 
    }); 
    } 
} 

storageServicce.ts

 console.log('addMessage: chat '+chat._id); 
     this.database.executeSql("SELECT * FROM chats where _id = " + chat._id, []).then((data) => { 
      let chats = []; 
      if (data.rows.length > 0) { 
       for (var i = 0; i < data.rows.length; i++) { 
        this.chats.push({ 
         _id: data.rows.item(i)._id 
        }); 
       } 
      } 
      console.log('addMessage: chats.length = ' + chats.length); 

輸出

addMessage: chat rSkFGaLgQ554FCCYJ 
ERROR: {"message":"sqlite3_prepare_v2 failure: no such column: rSkFGaLgQ554FCCYJ","code":0} 

問題

你知不知道爲什麼我收到錯誤?據我所知,錯誤所指的列是_id,但在創建數據庫時確實存在。

+0

可能重複的[SQLite插入問題 - 錯誤:沒有這樣的列](https://stackoverflow.com/questions/21958789/sqlite-insert-issue-error-no-such-column) – Veve

回答

2

您正在使用字符串從數據庫中進行選擇。該字符串不在引號中,因此預期它是一個列。這就是爲什麼錯誤表示該列不存在,並不是說_id不存在。

用單引號將值包裹起來,它會起作用。並確保它不是用戶指定的值,否則您將擁有SQL注入的可能性。使用參數。

+0

謝謝。我現在不在我的電腦裏。但稍後會檢查出來。 – Richard

+0

謝謝,這工作: 'this.database.executeSql(「SELECT * FROM messages where _id =?」,[data.rows.item(i).lastMessageId])。then((messageData)=> {' – Richard