How do I read data from a csv file and store it in my database file in sqlite?

advertisements

I have a static csv file. I want to covert all the data in the csv file to a database so that I can access the data in the csv file in my application. I have searched a lot about this. But still I'm was not able to find something that served my cause. Can somebody help me with this? Thank you.


i don't know of anything that's going to automatically take a CSV file and populate your database. at least, you need to map each value in the file to a DB row yourself. you are going to have to write your own code to process the CSV file (using a library or otherwise), and write the code to insert each CSV "row" into sqlite.

note that processing a CSV file for which you control the format is very simple. you can just use a FileRead and String.split(). then, again assuming that value N in a CSV row maps to col N in the DB, you can do,

private static final List<String> COLUMNS = new ArrayList<String>() {
  add("NAME"); add("ADDRESS"); add("ZIPCODE"); ...;
}

SQLiteDatabase db = ...;
BufferedReader br = new BufferedRead(new FileReader("foo.csv"));
String line;
while ((line = br.readLine()) != null) {
  Iterator cols = COLUMNS.iterator();
  String[] vals = line.split("\\s*,");
  ContentValues cv = new ContentValues();
  for (String v: vals) {
    cv.put(cols.next(), v);
  }
  db.insert(..., cv);
}

in this example, you must ensure that the order of the columns defined in COLUMNS matches exactly with the order of the values in each CSV row.