2017-06-01 71 views
-3

以下是我寫的SQLite表的聲明語句;Android中的SQLite插入語句;

db.execSQL("create table if not exists data(d text, hr integer, rrInterval real, acc_x real, acc_y real, acc_z real);"); 

所以這就是表data的樣子。

data{ 
    d text, 
    hr integer, 
    rrInterval real, 
    acc_x real, 
    acc_y real, 
    acc_z real 
} 

我用Microsoft Band 2測量了一些變量,存儲在以下變量中;我檢查了所有這些變量從MS Band獲取正確的數據。

String d; 
int heartRate; 
double rrInterval; 
float acc_x, acc_y, acc_z; 

所以這是一個用於存儲數據在SQLite數據庫。

MyOpenHelper helper = new MyOpenHelper(this); 
SQLiteDatabase db = helper.getWritableDatabase(); 

db.execSQL("create table if not exists data(d text, hr integer, rrInterval real, acc_x real, acc_y real, acc_z real);"); 


/* some other codes irrelevant to DB */ 

db.execSQL("insert into data(d, hr, rrInterval, acc_x, acc_y, acc_z) values ('" + 
    d + "', " +        //date 
    Integer.toString(heartRate) + ", " +  //hr 
    Double.toString(rrInterval)+ ", " +  //rrInterval 
    Float.toString(acc_x) + ", " +   //acc_x 
    Float.toString(acc_y) + ", " +   //acc_y 
    Float.toString(acc_z) +     //acc_z 
    ");"); 

據我所知,在Java和SQLite上都沒有語法錯誤。但Android Studio返回錯誤,這不是insert ...聲明。我怎樣才能弄清楚如何解決這個問題?

+3

'「但Android Studio返回錯誤」'它返回什麼錯誤?爲什麼不使用'SQLiteDatabase#insert()'方法? – pskink

+1

你的代碼對我來說工作的很好。我使用Android Studio 2.3.2 – sanemars

回答

1

而不是使用這種方法嘗試使用ContentValues更容易使用。

ContentValues cv = new ContentValues(); 
cv.put("d", DATA_NEEDED_TO_INSERT); 
cv.put("hr", DATA_NEEDED_TO_INSERT); 
cv.put("rrInterval", DATA_NEEDED_TO_INSERT); 
cv.put("acc_x", DATA_NEEDED_TO_INSERT); 
cv.put("acc_y", DATA_NEEDED_TO_INSERT); 
cv.put("acc_z", DATA_NEEDED_TO_INSERT); 
SQLiteDatabase db = getWritableDatabase(); 
db.insert(TABLE_NAME, null, cv); // insert function 
db.close(); // dont forget to close your db 

不要忘記db.close();過程後加入

+0

這段代碼沒有編譯:沒有'SQLiteDatabase#put()'方法 – pskink

+0

對不起我改變它插入 –