Im Working with SQLiteDatabase and i want to create only 1 row on the database, so i wana use if statement for this, my question is if there is a way to know if the database is empty or not.
Thank you!
EDIT:
I'll update my answer to help you a little bit further.
If you want to find out if the table exists and if it has rows:
Cursor query = myDB.rawQuery("SELECT count(*) FROM sqlite_master WHERE name = 'table1'", null);
if (query.moveToFirst()) {
// If that table exists, check if it has any rows
query = myDB.rawQuery("SELECT count(*) FROM table1", null);
if (query.moveToFirst()) {
// Table exists and it has rows. Do something with them here.
}
}
Related
I have two table in my sqlite db here is the first table named supplier and here is the second table named product
what I want to do is I want to get the supplier_name in table product by selecting id_supplier in table_product. Here is my query SELECT table_supplier.id_supplier, table_supplier.supplier_name from table_invoice_in, table_supplier where table_invoice_in.id_product = '4' and table_supplier.id_supplier = table_invoice_in.id_supplier
and what I got from that query is I can get the id_supplier but supplier_name gives me 0 value, but when I try the query in mysql, I got the correct result. My question is :
Is this a limitation of sqlite or there are something wrong with my query?
Thank you in advance.
Try using a JOIN:
SELECT table_supplier.id_supplier, table_supplier.supplier_name FROM table_supplier JOIN table_invoice_in ON table_supplier.id_supplier = table_invoice_in.id_supplier WHERE table_invoice_in.id_product = '4'
The problem solved! When we try to query some column(s) from multiple table, make sure that we get the desired result by pointing directly to the column name. Here is my correct code
public Cursor SelectInvoiceInById(String id){
String query = "SELECT product_name from table_product, table_invoice_in where table_invoice_in.id_invoice_in = '"+ id + "' and table_product.id_product = table_invoice_in.id_product";
ReadDB();
cursor = database.rawQuery(query, null);
cursor.moveToFirst();
if(cursor.getCount() > 0){
while (!cursor.isAfterLast()){
Log.d("RESULT", String.valueOf(cursor.getString(cursor.getColumnIndex(SQLiteHelper.PRODUCT_NAME))));
cursor.moveToNext();
}
}
CloseDB();
return cursor;
}
I am trying to fetch the last row from my SQLite database. Until now i have tried max,sql_sequence but nothing seems to work. I have to fetch the row values and assign it to a class variable.
Any help is appreciated as I am new to SQLite and Android.
Thanks..
If you have already got the cursor, then this is how you may get the last record from cursor:
cursor.moveToPosition(cursor.getCount() - 1);
then use cursor to read values
or
do it like this
Cursor cursor = db.rawQuery(selectQuery, null);
cursor.moveToLast();
or
SELECT * FROM TABLE WHERE ID = (SELECT MAX(ID) FROM TABLE);
This should do what you want:
SELECT *
FROM food_table
ORDER BY _id DESC
LIMIT 1
Try This It May Help You It Gives Last Record Of Your Table
Cursor mCursor = db.rawQuery("Select * from TableName", null);
mCursor.moveToLast();
Now Get The Data From The Cursor
There is usually a table called sqlite_sequence which stores the highest primary key of all the tables in the SQLite db. So use the following
String selectQuery = "SELECT * FROM sqlite_sequence WHERE name = table_name";
Cursor cursor = db.rawQuery(selectQuery, null);
cursor.moveToLast();
You can use modified query to in last row....but you have to sort in a order using any column like in my case I have a serial_no column in my Employee table so my query is
SELECT * FROM Employee ORDER BY serial_no DESC LIMIT 1
limit 1 is in your case because you want only last record only
I was trying to solve the question on why I was getting this error yesterday with some code:
java.lang.IllegalArgumentException: column '_id' does not exist
I had a lot more code, especially that I did not need, so I stripped a lot of it out to make it easier to understand where I am going wrong. But essentially this is my schema:
database.execSQL("CREATE TABLE events (" +
"_id INTEGER PRIMARY KEY, event_name TEXT" +
")");
As one can tell, looks fine right.
Unless I forgot to read, it's most obviously there. But then I figured out where my error was coming from, or at least I am sure this is why. This code that retrieves a cursor:
public Cursor getEventsName() {
return database.rawQuery( "SELECT event_name FROM events", null);
}
According to android, this is the error. When I change it to this:
public Cursor getEventsName() {
return database.rawQuery( "SELECT * FROM events", null);
}
Everything is peachy. When the former, it crashes. Any reason as to why this is. I thought that in rawQuery() I could do that. So long as I am not including where clauses, which I am not. Any help much appreciated.
Let's call these, event cursor:
public Cursor getEventsName() {
return database.rawQuery( "SELECT event_name FROM events", null);
}
... and * cursor:
public Cursor getEventsName() {
return database.rawQuery( "SELECT * FROM events", null);
}
Most of the answers that you have received (even the ones here: In Android, does _id have to be present in any table created?) are guessing at the likely cause for your error. I figured I would answer your question as well:
Any reason as to why (the former crashes and the later is peachy?)
The difference between the * and event cursors is that * is selecting every column implicitly and event is only selecting event_name. In your events table, the * cursor is the equivalent of:
SELECT _id, event_name FROM events;
which is why the this cursor works just peachily. In other words you are not receiving this error:
java.lang.IllegalArgumentException: column '_id' does not exist
because you are implicitly selecting the _id column with *.
Of course the most probable reason for getting this error is when you bind your data with a ListView, Spinner, etc; they all tend to use a CursorAdapter of some form. This is from the CursorAdapter documentation:
Adapter that exposes data from a Cursor to a ListView widget. The Cursor must include a column named "_id" or this class will not work.
So the Solution is simple: you must select the _id column in your query as well as the other columns that you want. (The compiler isn't lying to you.)
That being said, if this still doesn't seem valid to your app or doesn't make sense please post the code where you use the Cursor and the error is thrown.
I suspect that whatever was handling the cursor was trying to get the _ID column but it wasn't specified in your select statement. Doing something like,
public Cursor getEventsName() {
return database.rawQuery( "SELECT _id, event_name FROM events", null);
}
Some Android components, such as the SimpleCursorAdapter require the _ID be available in the select statement since it uses internally when getItemId() is called.
java.lang.IllegalArgumentException: column '_id' does not exist
I had same problem, this exception is thrown because SimpleCursorAdapter need for SELECT column named _id so you can resolve it when for example if you created some table with column KEY_ID as PK so you can try it like this:
SELECT KEY_ID AS _id, column1, column2 FROM SomeTable.
public Cursor getEventsName() {
return database.rawQuery( "SELECT * FROM events", null);
Change it to
public Cursor getEventsName(){
final String[] columns = new String[]{"_id", "event_name "};
return database.query(events, columns, "" , null, null, null, null);
}
I have two tables in my database table1, table2. I have a join query like this:
select a.*,b.* from table1 a,table2 b where a.field1=b.field1;
Its working fine while i test it in sqlite manager(sqlite browser). when i try to make it through java like this:
database.execSQL("select a.*,b.* from table1 a,table2 b where a.field1=b.field1;");
its saying return type is not cursor. How can i get it to cursor with join. I have to get that data and show in a listview
use like this:
String qry = "select a.*,b.* from table1 a,table2 b where a.field1=b.field1";
Cursor cur = db.rawQuery(qry,null);
String query = "select a.*,b.* from table1 a,table2 b where a.field1=b.field1;";
Cursor c = database.rawQuery(query, null);
/* do whatever you want with 'c' */
Following is an Example of rawQuery, you can add your Query Respectively.
String getRT = "SELECT count(*) from "+ DATABASE_PROFILE+";";
Cursor mCur = sqlitedb.rawQuery(getRT, null);
return mCur;
SQLiteDatabase.rawQuery(query, selectionArgs)
Use rawQuery method to design any sort of complex query you might need. In the reference there are many useful methods you might need.
When I insert a row into a full-text search database declared like:
CREATE VIRTUAL TABLE foo USING fts3 (bar);
the SQLiteDatabase.insert() method returns an incorrect rowid. If the table is declared like:
CREATE TABLE foo (bar VARCHAR(10));
it returns the correct rowid value. The problem is when I query the database soon after the insert using the rowid returned from the method, the returned Cursor has no records. It works correctly for the first insert into the database only. For subsequent inserts, an incorrect rowid is returned.
Is there anything I need to do to get the correct rowid from the SQLiteDatabase.insert() method?
I'm using Android SDK version 2.1update1.
Thanks,
Dan
Update:
I ended up using a hack to get the last row id using the following code:
private int getLastRowId(SQLiteDatabase db, String table) {
Cursor cursor = null;
try {
cursor = db
.rawQuery(String.format(Locale.US, "SELECT MAX(rowid) FROM %s", table), null);
if (cursor.moveToFirst()) {
return cursor.getInt(0);
} else {
return 0;
}
} finally {
if (cursor != null) {
cursor.close();
}
}
}
In my case, it's safe because only a single user has access to the app. For service apps, this may not work depending on how it is implemented/used.
I believe we have this problem because when performing an insert in fts3 tables, more than one row is inserted. A row is inserted in the subject table and in the fts3 management tables as well.
From SQLite Full-Text Search:
Your table must contain at least 1
TEXT field.
PS: +1: I didn't know about Virtual Tables. Thanks.