我試圖將數據從csv文件傳輸到我的應用程序上的數據庫。 csv文件不是從我的數據庫生成的,所以有些字段我不感興趣傳輸。我會怎麼做呢?將csv導入數據庫
CSV:日期,參考文獻,數量,類型,顏色,類別
DB:日期,數量,顏色,類別
我試圖將數據從csv文件傳輸到我的應用程序上的數據庫。 csv文件不是從我的數據庫生成的,所以有些字段我不感興趣傳輸。我會怎麼做呢?將csv導入數據庫
CSV:日期,參考文獻,數量,類型,顏色,類別
DB:日期,數量,顏色,類別
嘗試這樣的事情......
FileReader fr = new FileReader(fileName);
BufferedReader br = new BufferedReader(fr);
String data = "";
String tableName ="MY_TABLE";
String columns = "date,quantity,color,category";
String InsertString1 = "INSERT INTO " + tableName + " (" + columns + ") values(";
String InsertString2 = ");";
db.beginTransaction();
while ((data = br.readLine()) != null) {
StringBuilder sb = new StringBuilder(InsertString1);
String[] sarray = data.split(",");
sb.append("'" + sarray[0] + "',");
sb.append(sarray[2] + "',");
sb.append(sarray[4] + "',");
sb.append(sarray[5] + "'");
sb.append(InsertString2);
db.execSQL(sb.toString());
}
db.setTransactionSuccessful();
db.endTransaction();
若要打包靜態數據,使用任何UI或csv-import command在開發時,船舶此sqlite db file into asset folder,然後,您可以copy the entire sqlite file onto the device when your application is first run.
在運行時插入了大量的數據,bulk insert using transactions是最好的性能
您還可以使用BufferReader
BufferedReader in = new BufferedReader(csvfilepath);
String reader = "";
while ((reader = in.readLine()) != null){
String[] RowData = reader.split(",");
對於Java程序員,DBIS是非常有用的。你可以在沒有單行代碼的情況下實現。 檢查下面。
發佈CSV的形狀和表格的形狀。 – 2011-04-21 03:18:05