Is there an easy way to import data into SQLite? - android

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.

Related

Android Sqlite transfer table from one database to another

I've a requirement in my android app.
There is an already existing database A which has a table T. From the next release of the app, I want to create a new database B and MOVE my table from A to B WITH all the existing data.
I am guessing there'd be some way to take dump from the existing db and store that in an asset file. And then use that file to restore the table in new db.
Can't store that data in-memory as it might go to inconsistent state if the app is killed in between.
I am not able to find any well-defined way to do this after spending some time searching in the docs/on the forums.
Please help.
You can achieve this by using ATTACH command of sqlite. First is by specifying the path of the first database.
private static String FIRST_DB_PATH = context.getDatabasePath("Sample.sqlite").toString();
Then you attach it to secondDb
SQLiteDatabase secondDB = secondDBHandler.getWritableDatabase();
secondDB.execSQL("ATTACH DATABASE '" + FIRST_DB_PATH + "' AS tempDb");
Then do the insert query. NOTE: You use secondDB as main
secondDB.execSQL("INSERT INTO main." + SeconDB_table_name + "SELECT * FROM tempDb."+ FirstDB_table_name );
Then finally detach the first db
secondDB.execSQL("DETACH tempDb");
Hope this helps
EDIT:
Do this for dropping table
secondDB.execSQL("DROP TABLE IF EXISTS main." + SeconDB_table_name);
Ok heres how to create a table for secondDB as a copy of the firstDb
secondDB.execSQL("CREATE TABLE main." + SeconDB_table_name + " AS SELECT * FROM tempDb." + FirstDB_table_name);
If what you mean in comment is to drop the first table after moving it to second table, then drop it before dettaching
secondDB.execSQL("DROP TABLE IF EXISTS tempDb." + FirstDB_table_name);

Import table into existing sqlite database 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

How to search in android sqlite database with speedy way?

i tried to search in the sqlite database using the below code :
Cursor cusror;
cursor=db.rawQuery("SELECT * FROM "+ Contactsnew.TABLE02 + " WHERE "
+ Contactsnew.userid + " = " + Contactsnew.userId + " AND " +
Contactsnew.TITLE +
" LIKE '"+search.getText()+"%'");
its working successfully , but in huge database its working slowly. i searched the last days to find third library to work with my own database (Copied from assets to sqlite database) .
i find top five libraries in this article i followed each library but what i find each database is working only with the database that created by itself not with existing database (Already copied from assets).
any help to use any of these library and refer it to my own database or any another library to help me .
Thanks
I suggest creating prepared statements and re-use them. There is an excellent answer on Stack Overflow how to do that. Consider reducing the columns returned by the query, if not all columns are needed. Further, consider creating indexes for relevant columns. test would be the table name and id a column name:
CREATE INDEX idx01 ON test(id);
As a last resort it might be worth trying to remove the LIKE completely and to the regex test while iterating over your cursor.
You have to make sure existing database has the same format of data as new database you adding.
Probably, the simpliest solution here - write some 'migration utility', which will extract existing data and save it to new database.
To speed up queries store different aspects of data into separate tables (not everything in single table), or, if your data has many dependencies, try noSql database (Realm) which not using tables.

Android SQLite, create db with 4 columns and insert values

I am missing something with all of the android SQLite tutorials.
I want to create a SQLite database that holds the autoincrementing key, and four text fields that I will pass in
I intend to pass in this SQL database
private static final String INSERT = "insert into " + TABLE_NAME + "(field1) values (?)" + "(field2) values (?)" + "(field3) values (?)";
but I'm not sure if the android sdk has a proper insert function.
I'm not sure how "Cursor" relates to anything I am trying to do, and I'm not sure how much object oriented initializing I should be trying to as opposed to just calling some built in android sdk functions.
insight appreciated, but please break it down
Will recommend you to go through NotePad exercise here is a link. Specially go through Exercise 1.
And for more depth knowledge you can go through project which I have created. Here is a link
Look for creatFeed function call here. I think will help to answer your problem.

Android SQLite, some SQL basics

I am following this tutorial: http://www.codeproject.com/KB/android/AndroidSQLite.aspx
I must be overthinking this SQLite stuff (in the past my domain server would automatically initialize databases I requested, and I could do queries when desired. never put one together from scratch)
I have some questions about their onCreate function. I never recall using a
CREATE TRIGGER command in my SQL
I only need to create one table with 2 or 3 columns (if you count the primary key)
I should just be able to do
db.execSQL("CREATE TABLE" + tableName +"("+colID+"INTEGER PRIMARY KEY,"+columnName+"TEXT)");
correct?
Do I need a "Trigger" and a "View" ?
If you just need a place to store some data - then Table is enough. But if your logic is more complicated then you'll need additional stuff. Also note that some Triggers are not supported by SQLite: Info from here
You not need to create TRIGGER. Unless it is required. Here is how I implemented in one of my project. Hope this help.
https://github.com/gopalB/FeedReader/blob/master/src/com/feedReader/provider/FeedDB.java
If you do not need a Trigger or a View, then you do not need to create them. It appears that the tutorial is just explaining some of the things you can do.
if SQLite TRIGGER and VIEW are similar to what they're used for in MySQL then no, they are not necessarily for what you're trying to accomplish.
VIEWs are useful when you have complex queries (like when using JOINs to join data from multiple tables).
TRIGGERSs are conditions that are run when you modify a table. (like using UPDATE, or INSERT)
As written, your create statement won't work because of a lack of whitespace. Try:
db.execSQL("CREATE TABLE " + tableName +" (" + colID + " INTEGER PRIMARY KEY, " + columnName + " TEXT)");

Categories

Resources