Android應(yīng)用中如何將數(shù)據(jù)插入到SQLite數(shù)據(jù)庫(kù)?相信很多沒(méi)有經(jīng)驗(yàn)的人對(duì)此束手無(wú)策,為此本文總結(jié)了問(wèn)題出現(xiàn)的原因和解決方法,通過(guò)這篇文章希望你能解決這個(gè)問(wèn)題。
1、使用db.execSQL(sql)
這里是把要插入的數(shù)據(jù)拼接成可執(zhí)行的sql語(yǔ)句,然后調(diào)用db.execSQL(sql)方法執(zhí)行插入。
public void inertOrUpdateDateBatch(Listsqls) { SQLiteDatabase db = getWritableDatabase(); db.beginTransaction(); try { for (String sql : sqls) { db.execSQL(sql); } // 設(shè)置事務(wù)標(biāo)志為成功,當(dāng)結(jié)束事務(wù)時(shí)就會(huì)提交事務(wù) db.setTransactionSuccessful(); } catch (Exception e) { e.printStackTrace(); } finally { // 結(jié)束事務(wù) db.endTransaction(); db.close(); } }
2、使用db.insert("table_name", null, contentValues)
這里是把要插入的數(shù)據(jù)封裝到ContentValues類中,然后調(diào)用db.insert()方法執(zhí)行插入。
db.beginTransaction(); // 手動(dòng)設(shè)置開(kāi)始事務(wù) for (ContentValues v : list) { db.insert("bus_line_station", null, v); } db.setTransactionSuccessful(); // 設(shè)置事務(wù)處理成功,不設(shè)置會(huì)自動(dòng)回滾不提交 db.endTransaction(); // 處理完成 db.close()
3、使用InsertHelper類
這個(gè)類在API 17中已經(jīng)被廢棄了
InsertHelper ih = new InsertHelper(db, "bus_line_station"); db.beginTransaction(); final int directColumnIndex = ih.getColumnIndex("direct"); final int lineNameColumnIndex = ih.getColumnIndex("line_name"); final int snoColumnIndex = ih.getColumnIndex("sno"); final int stationNameColumnIndex = ih.getColumnIndex("station_name"); try { for (Station s : busLines) { ih.prepareForInsert(); ih.bind(directColumnIndex, s.direct); ih.bind(lineNameColumnIndex, s.lineName); ih.bind(snoColumnIndex, s.sno); ih.bind(stationNameColumnIndex, s.stationName); ih.execute(); } db.setTransactionSuccessful(); } finally { ih.close(); db.endTransaction(); db.close(); }
4、使用SQLiteStatement
查看InsertHelper時(shí),官方文檔提示改類已經(jīng)廢棄,請(qǐng)使用SQLiteStatement
String sql = "insert into bus_line_station(direct,line_name,sno,station_name) values(?,?,?,?)"; SQLiteStatement stat = db.compileStatement(sql); db.beginTransaction(); for (Station line : busLines) { stat.bindLong(1, line.direct); stat.bindString(2, line.lineName); stat.bindLong(3, line.sno); stat.bindString(4, line.stationName); stat.executeInsert(); } db.setTransactionSuccessful(); db.endTransaction(); db.close();
第三種方法需要的時(shí)間最短,鑒于該類已經(jīng)在API17中廢棄,所以第四種方法應(yīng)該是最優(yōu)的方法。
看完上述內(nèi)容,你們掌握Android應(yīng)用中如何將數(shù)據(jù)插入到SQLite數(shù)據(jù)庫(kù)的方法了嗎?如果還想學(xué)到更多技能或想了解更多相關(guān)內(nèi)容,歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道,感謝各位的閱讀!