This question already has an answer here:
Closed 11 years ago.
Possible Duplicate:
sqlite example program in android
Hi I'm new to android and I am having some trouble finding a good tutorial for an SQLite database. What I wanted to do was to store a line of data in the database, reference it later and then delete it once its been referenced. As I have said I am new to this sort of thing and have no clue even what any of the syntax is so if there is a simple tutorial out there I would like to know.
try this
try { // creating a database called db and a Table inside it, called
// userdetails. With username and password as columns.
db = openOrCreateDatabase("UserDetails.db",
Context.MODE_PRIVATE, null); // optional CursorFactory
db.execSQL("drop table if exists userdetails");
db.execSQL("create table userdetails " + " ( username TEXT,"
+ "password TEXT);");
} catch (SQLException x) {
x.printStackTrace();
Log.e(LOG_TAG_NAME, "Database creation error");
}
//.........................................................................
// and insert values into the database table.
try {
db.execSQL("INSERT INTO " + "userdetails"
+ " (username,password)" + " VALUES ('hi','hello');");
db.execSQL("INSERT INTO " + "userdetails"
+ " (username,password)" + " VALUES ('chris','gayle');");
db.execSQL("INSERT INTO " + "userdetails"
+ " (username,password)" + " VALUES ('v','v');");
} catch (Exception e) {
e.printStackTrace();
Log.e(LOG_TAG_NAME, "inserting table values error");
}
String[] columns = { "username", "password" };
Cursor c = db.query("userdetails", columns, null, null, null, null,
null);
now use the cursor to retrieve values
also have a look at
http://developer.android.com/guide/topics/data/data-storage.html#db
hope all this helps
EZ Answer I think.
If I understand your needs I think that you will find a database is overkill. You can do this a lot easier I think with just a few lines of code. If I am correct, a "line of data" sounds like a single String that you want to persist. If that is the case SharedPreferneces is by far your best bet for easy implementation.
Check out THIS link to the Dev-Guide's Shared Preferences Data Storage section
Its as easy as initializing the Preferences, and either putting or asking for a value by key.
On the other hand if you need to store many lines of relational data, search through them, sort them, etc. then a database is what you want.
Generally, I choose the data storage mechanism based on what is being stored and how i want to retrieve it:
Single primitives (and Strings) get stored best in SharedPreferences.
This is a fast and easy implementation. You can get away with storing a couple of values if you need to to represent a more complex class. Sometimes it makes sense to create a helper class that keeps track of complex schemes.
Serializable complex data, like parameterized Collections, that are loaded into memory all at once, long streams of text to be parsed, or if that data is a byte stream it gets stored to a file. This is not as fast and involves catching a lot of potential IO issues. But most objects are serializable or easily made that way.
Tables of data that I want to query or provide a Cursor for because of how long they are go into a database. The start up and resource expenses of a database are huge. Writing all the helper code to use them is a pain in the extreme.
Complete Step by Step SQLite Example:
http://mobile.tutsplus.com/tutorials/android/android-sqlite/
Youtube Video Tutorial
http://www.youtube.com/watch?v=kMaBTolOuGo
Multiple Table Creation
http://androidforbeginners.blogspot.com/2010/01/creating-multiple-sqlite-database.html
PS: All the links are tested and working well!!
Happy Coding!!
First place to look for tutorials should be the official Android Docs: Link.
Related
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.
Here is the table where i want to insert the value:
" create table if not exists "+CipherCongfigTable +
" ( DATABSE_NAME **TEXT** PRIMARY KEY NOT NULL,DATABSE_KEY **TEXT** NOT NULL);";
when i want to insert
String **configDBPassword**= "**x\'2DD29CA89\'**"
through statement
"insert into "+CipherCongfigTable+ " values("+DataBaseName+","+**configDBPassword**+")"
I am getting exception:
unrecognized token: "\":
I need the password in the same format i.e. having escape charecter. Is there any way to do it????
Thanks
Don't manually build INSERT (or any other if you can avoid it) queries on Android (or any other database wrapper as long as there is a predefined API to get what you want). It opens up your application to quoting problems like the one from your question and --at the worst-- to SQL injection attacks from outside of your application.
For example, setting configDBPassword = "\"; DROP TABLE <tablename>; --" I could possibly wreak havoc on your database as long as configDBPassword can be entered by the user.
Also, SQLite uses double quotes ("), backticks (`, borrowed from MySQL), or square brackets ([], borrowed from MS SQL) to quote identifiers (e.g. column or table names with spaces in them), string literals are canonically quoted with single (') quotes. SQLite is a quite liberal in allowing to mix both quoting types, but it is significantly more readable to use the proper quoting style whereever appropriate. From the documentation:
Programmers are cautioned not to use the two exceptions described in the previous bullets. We emphasize that they exist only so that old and ill-formed SQL statements will run correctly. Future versions of SQLite might raise errors instead of accepting the malformed statements covered by the exceptions above.
As a matter of fact, you should avoid doing the quoting by yourself whenever possible. For inserting values, please instead use SQLiteDatabase.insert() which is the proper way of inserting values into an SQLiteDatabase on Android. It also does proper quoting of the arguments, too:
db.beginTransaction();
try {
final ContentValues values = new ContentValues();
values.put("DATABSE_NAME", DataBaseName);
values.put("DATABSE_KEY", configDBPassword);
db.insert(CipherCongfigTable, null, values);
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
Always properly quote your SQL parameters.
Try this .
"INSERT INTO "+CipherCongfigTable+ " values('DataBaseName','configDBPassword')”
You are not adding Single quotes(') in your insert query
Edit :
If you need to insert string with Single qotes means use like this before insert.
configDBPassword = configDBPassword.replace ("'", "''");
Also change your **
" create table if not exists "+CipherCongfigTable +
" ( DATABSE_NAME TEXT PRIMARY KEY NOT NULL,DATABSE_KEY TEXT NOT NULL);";
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.
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.
I have a database with five tables in an Android application. I have been surfing around looking for a way to put conditions in the query (WHERE, &&, OR).
My queries are the form:
public Cursor getAlternative(int questionid) {
Cursor cursor = mDb.query(DBTABLE_ALTERNATIVE, new String[] { KEY_ALT }, KEY_QID + "=" + questionid, null, null, null, null, null);
return cursor;
}
But I find that many people write their queries with regular SQL, for ex:
Cursor c = myDB.query("SELECT FirstName,Age" +
" FROM " + MY_DATABASE_TABLE
+ " WHERE Age > 10 LIMIT 7;",
null);
What is the most efficient way? To me it seems easier form regular SQL statements, but after reading the tutorials on the Android Dev site I started forming the queries like above.
Question 2: if I use the first way, how can I use two conditions? Say I have two parameters, questionid and categoryid, how do I put the next KEY_CID + "=" + categoryid in there?
I have tried with && and AND but none seem to work. Thanks.
What is the most efficient way?
It depends... but generally speaking the second way will be faster. Why? because it won't need to build the query string using the parameters that the query method takes.
However, I'd rather use the first way since it's less error prone.
Question 2. If I use the first way, how can I use two conditions?
It should work this way:
KEY_QID + "=" + questionid + " AND " +KEY_CATID + "=" + categoryid
I am not sure if the simple implications about String and StringBuffers (StringBuilder would even better) hold, as the SQL engine also needs to parse that query string again.
The db.query() way may have the advantage that some parts of the query can be stored in a pre-parsed way (think "PreparedStatement"). Especially if the parameters are not put in the string, but as placeholders
E.g. where KEY_QID=? AND KEY_CATID=?
Here the basic query "stays constant" and the system can optimize.