Insert a table of integers - int[] - into SQLite d

2019-06-16 09:27发布

问题:

Is it possible to insert a table of integers like int[] numbers into an SQLite Table ?

How to create the column where I put this table?

this line of code:

values.put(MySqlHelper.COLUMN_CHILDS, numbers);

Returns me an error like:

Change type of `numbers` to `String`

回答1:

There is no array datatype in SQLite. You have two options:

Create 2 different tables, a "primary" table and a "numbers" table, where the numbers refer to a record (row) on the "primary" table via a foreign key.

(easier but not ideal): As @CloudyMarble suggests, Use Arrays.toString(numbers) (or a StringBuilder if for some reason that doesn't fit your needs) to put all of the numbers in your array into a comma-separated String and store that in your database. You can then pull that value back from the database into a Java array like so:

 String[] s = stringFromDB.split(",");
 int[] numbers = new int[s.length];
 for (int curr = 0; curr < s.length; curr++)
     numbers[curr] = Integer.parseInt(s[curr]);


回答2:

insert your numbers array as a string:

Arrays.toString(numbers);

And on reading split the array using the split method and convert elements to integer as @drewmore's answer show.