Import table into existing sqlite database android - android

I am in a situation where the user has a sqlite database that has data that should not be tampered with at all. Essentially I want to import a table from a .csv file or something along those lines into their database without touching any of the data.
I notice that there is no library frmo what I can see that does explicitly this. My knowledge with SQLite isn't as comfortable as I'd like it to be so I'm unsure of where to go here.
Should I just read the file line per line copying the data and then inserting it into the created table? Each table will have 400 records, not too many so I figure it can't be that inefficient. My inexperience is what worries me thinking I will somehow damage the data. Hoping to prevent mistakes and liability here..

Here's one way:
Create a new temporary database table without a primary key (so you can verify it before copying it.)
e.g.
CREATE TABLE salespeopleTMP (
id INTEGER,
first_name TEXT NOT NULL,
last_name TEXT NOT NULL,
commission_rate REAL NOT NULL
);
and there is existing data in the table that looks like this:
sqlite> select * from salespeople;
1|Fred|Flinstone|10.0
2|Barney|Rubble|10.0
If I now have a CSV data file named people.txt that looks like this:
3,John,Doe,5.0
4,Jane,Smith,5.0
Import the CSV data into that temporary SQLite table
You can import the CSV data into my SQLite table with these two commands:
sqlite> .separator ','
sqlite> .import people.txt salespeopleTMP
Use the INSERT INTO command to import the data from your temporary
table into your actual table
insert into salespeople select * from salespeopleTMP
Delete your temporary table salespeopleTMP
based on and bug fixed from https://alvinalexander.com/android/sqlite-csv-import-data-table-primary-key

Related

SQLite Check if Table is FTS4

I'm developing an Android app that uses a SQLite database with FTS4 tables.
In the app there's an option to import a database from the external memory. This database needs to be checked to confirm that it has all the correct tables and columns. I already have the code to do that however I don't know how to check if the tables are "normal" or FTS4. This will result in problems later on with queries with MATCH on them.
The only way I can think of to check if the tables are FTS4 is to do a random query with MATCH and if it gets an error it's because they are not.
Is there a better way to do this like with just a command?
Using MATCH on a plain table results in an error message only if the table has at least one row.
FTS table have a virtual column with the same name as the table name. So you could try a query like SELECT MyTable FROM MyTable.
You could check whether the shadow tables (MyTable_content, MyTable_segdir, etc.) exist.
You could check the CREATE TABLE statement in the system table: SELECT sql FROM sqlite_master WHERE type = 'table' AND name = 'MyTable';

Changing a Column type in my Android App's Database

I have an app published in the play store.
The app uses a database which holds a table which has a column of type int.
I'm doing a new change where I need to change the column type to long.
How do I go about handling it in the DatabaseHandler I'v created.
I want to preserve the data stored in the older apps database, so what should ideally be the code in the onUpgrade() function???
You don't need to change the database column type. An INTEGER column will happily contain all the bits needed to represent a Java long.
In fact, there's no long column type in sqlite.
I think using SQLite, the best way is to create a temporary table, copy all your table content, drop the old table and recreate the table with the right type on your column, then you can just copy the content from the temporary table and drop it...
I know this don't fell like the best approach, but I don't think SQLite have some alter table function.
As far I know you can t do this . But You can drop your table if it exists and create it again . Maybe you can find out some useful information here SQLite Modify Column or here Modify a Column's Type in sqlite3

How to dump a row from a SQLite database and import it into another database?

I currently want to dump a row from a SQLite database, transfer it over a network, and import it into the SQLite database on another phone. How would I properly dump the row and import it later? I looked around and I see a number of people mentioning .sql files, but is there an Android-specific way to do it? Thanks.
I assume that you have exact same table structure on both source and target sides (otherwise question would not make much sense), and you probably already know your table structure.
In that case, if you simply SELECT row you want to export (for example using Java code):
SELECT * FROM mytable WHERE id = 12345;
you would know row contents, so you can construct INSERT statement for target table, which should look like this:
INSERT INTO mytable ( col1, col2, ...)
VALUES ('val1', 'val2', ...);
All you need now is to execute this insert statement on target side (using Java or sqlite3 command line).

Am I understanding how to import my .csv file into sqlite?

I currently have a .csv file with several unlabeled columns of data, which to my knowledge translate to the following datatypes in sqlite:
datetime (in the format 7/19/2011 12:00:00 PM) -> numeric
double -> real
char(1) -> text
float -> real
I can create the database by doing the following:
sqlite> create table myTable (myVar1 numeric, myVar2 real, myVar3 text, myVar4 real);
sqlite> .separator ","
sqlite> .import myFile.csv myTable
Then I copy and paste the newly created myTable.db into the "assets" folder in my project in eclipse. I make a DatabaseHelper class that extends SQLiteOpenHelper, and then I can start using and reading from the database in my Android project.
Am I getting this right? I've never used a database before and I've seen so many vastly different instructions on doing this. Some of my questions are-- do I have to label the columns of my .csv file? Is my .csv file not "simple" enough to just use .import and I'll need to find a program to translate it? I've come across sites saying that I need to rename something (which I don't seem to have) to "_id", and I don't know what this is, where this is, or how to do this, or if it's even necessary, or what it's for. What else am I missing?
I think you are getting it "right" except for that first datetime column. You should use the TEXT type, not a numeric type.
Also, you can inspect your data after the import to see if all is well, especially with that datetime field:
SELECT * FROM myTable ORDER BY RANDOM() LIMIT 10;
UPDATE
In response to the OP's last comment: my understanding of how you store date(time) is that it depends on your context. So if the date in the flat file is in the format "7/19/2011 12:00:00 PM", then without any transformation it'll be imported as TEXT anyway.
Importing csv into database is 15 lines of code task and it gives you more control over this process.
Table columns names like "var3" are just terrible, however there is no need to rename it in database you can just use sql aliases:
select myVar1 _id, myVar2 from myTable
_id is common name for primary key column of table (it's usually numeric column witch must be unique). Every ADK class using datastore assumes relays on it, so it's nice to use this convention.
If you just want read only database you can prepare db locally and find some tutorials how to include it into your app.

Is there an easy way to import data into SQLite?

At the moment I am having to write out each query to insert data into the database separately.
Is there a way I can import a spreadsheet or anything else and end up with this form.?
Is there an auto-increment feature like in normal MySQL?
db.execSQL("INSERT INTO " +
SAMPLE_TABLE_NAME +
" Values ('3','" +
"Question'," +
"'Answer1'," +
"'Answer2'," +
"'Answer3'," +
"'Answer4'," +
"'Correctanswer'," +
"'Reason');");
Also is there an autoincrement feature like in normal Mysql?
Yes. Take a look at: http://www.sqlite.org/autoinc.html
With regards to your original question; for those cases I better create the database and the initial data in my computer using any of the Sqlite DB Managers out there. Then, I put the database inside the assets directory of the project and instead of creating the database the normal way, I copy the database from there to the handset. This like could be helpful in that case:
http://www.reigndesign.com/blog/using-your-own-sqlite-database-in-android-applications/
If you can use the SQLite Command Line Shell to prepare your database, you can .import into a table from a file
If your data is (contained in) a spreadsheet, consider using the spreadsheets scripting/macro language to export table(s) INTO a SQLite database
For lots of tables preparing a master database and attach-ing to that from your app may be more efficient and could be done on the handset only
wrt to autoincrement, look at the autoincrement faq too
If I understand, you want to initialize your database with some values, but you don't want to hardcode each query.
In this case you should use JSON to store your data in an external file (like a spreadsheet), then parse this file to get your data and use it to generate your SQL queries.
Here is a tutorial on how to use JSON in android apps.

Categories

Resources