Counting text matches in sqlite - android

I am querying several columns in a table for some words (essentially querying m text columns whether they contain n terms which are entered by the user), and I want to rank these rows by how many matches occur.
So I have something like this query :
SELECT *, (COLUMN1 LIKE '%TERM1%') + (COLUMN1 LIKE '%TERM2%') + ... + (COLUMN1 LIKE '%TERMN%') + (COLUMN2 LIKE '%TERM1%') + ... + (COLUMNM LIKE '%TERMN%') AS SCORE
FROM TABLE_NAME
WHERE COLUMN1 LIKE '%TERM1%' OR ... OR COLUMNM LIKE '%TERMN%'
ORDER BY SCORE DESC LIMIT 200;
But this query does not seem to work all the time, sometimes all the results seem to have score 0, even when there are matches. Can anybody suggest what the problem is? I suspect it might be something to do with the type of result of LIKE operator and the type of score column.
Also, is there some better way of doing the same thing without generating this verbose query?

yes there another way using code
try this
long cnt = countdata("COLUMN1 LIKE %TERM1%")
:
public Long countdata(String whereClause) {
long count = 0;
Cursor c = mDb.rawQuery("SELECT count(*) FROM TABLENAME WHERE " + whereClause, null);
int numRows = c.getCount();
c.moveToFirst();
for (int i = 0; i < numRows; ++i) {
Log.i("Count", c.getString(0));
count = c.getLong(0);
c.moveToNext();
}
c.close();
return Long.valueOf(count);
}

Related

How to efficiently query sqlite database multiple times on Android

For my application, I need to query a sqlite database around 40-50 times. I am sure that the code I wrote is very inefficient. Unfortunately, I cannot find many examples online that involves querying the database many times.
String[] entryValArray = new String[indicesList.size()];
DBHelper dbHelper = new DBHelper(MainActivity.context);
SQLiteDatabase db = dbHelper.getReadableDatabase();
for (int i = 0; i < indicesList.size(); i++) {
int moddedIndex = Integer.parseInt(indicesList.get(i), 16) % DBHelper.numEntries;
String queryStr = "select * from " + DBHelper.TBL_NAME + " where " + DBHelper.IDStr +
" = " + Integer.toString(moddedIndex);
Cursor cursor = db.rawQuery(queryStr, null);
if (cursor.moveToFirst())
entryValArray[i] = cursor.getString(1);
cursor.close();
}
Basically, I am taking a list of strings, converting them to hex values, and then modding the value to get an index into a sqlite database. This is for a password generator application.
Is there a better way to do this, especially regarding creating a cursor and then closing it in every iteration.
First of all you have to change your query string as you need only one column value but you are using
Select *
instead of
Select yourColumn
. Secondly if your indices list size is not very large you can use
IN(values ) function of db instead of
" where " + DBHelper.IDStr +" = " + Integer.toString(moddedIndex);
this will return the result in only one query you don't have to run a whole loop.

sqlite android select sum

my table look like this:
Client_Code Oder_ID NoOrd Weight
850458 5 1 12
850458 5 2 12
850458 6 1 5
i want to sum the Weight, but unique par Oder_ID.
so the resultat that i want is 17 = 12 + 5
not 29
how can i do that ?
my code like this;
public int GetPoids()
{
String SQL_syntax = "SELECT SUM("+ DBHelper.KEY_Poids +") as SumPoids FROM " + DBHelper.tableName + " GROUP BY " + DBHelper.KEY_CodeClient +","+DBHelper.KEY_NoOrdre ;
Cursor c = database.rawQuery(SQL_syntax, null);
if (c != null)
c.moveToFirst();
int Poids = c.getInt(0);
c.close();
return Poids;
}
Give a try, First you need to get unique OrderIds then take only one record of that OrderId with one more condition NoOrd=1 (it must have atleast NoOrd=1 in each record)
select sum(Weight) from Table_Name where Order_ID in (select distinct Order_ID from Table_Name) and NoOrd=1
Sorry if it doesn't help you, actually I tried on a online tool due to lack of your database structure.

how to update sqlite using expression?

I would like to do this query in SQLite:
update table1 set col1 = (? || substr (col1, col2))
where table1.id in (select id from table2 where condition);
I'm not sure how to do this. SQLiteDatabase.rawQuery doesn't work. All the other APIs I've seen don't allow the expression in the "set" part. If I could use SQLiteStatement, it would work. But that constructor is only visible in its package, not to my code :(
Ideally, I would do something like this:
String query =
"update Table1 set " +
" col1 = (? || substr (col1, col2)), " +
" col2 = ? " +
"where Table1.id in " +
" (select id from Table2 where col3 = ?)";
String[] args = new String[3];
args[0] = arg0;
args[1] = arg1;
args[2] = arg2;
SQLiteStatement statement = new SQLiteStatement (getDb(), query, args);
int rowsUpdated = 0;
try
{
rowsUpdated = statement.executeUpdateDelete();
} finally {
statement.close();
}
Any ideas? Thanks.
Usually when we want to run CRUD operations we use SQLiteDatabase.execSQL().
SQLiteDatabase.rawQuery() is generally used for select queries and it returns a Cursor with the result set.
Although rawQuery() should theoretically work because according to the docs
Runs the provided SQL and returns a Cursor over the result set.
But others have reported that it doesn't work with update queries, so I'm not entirely sure about that.

Android: SQLite, How to Select count(*) from multiple tables?

If I use cursor, I can't use "cursor.getString" with the following code.
And I found that "Cursor.count = 0".
But if I execute this code in the adb shell, I can get the result "10|15|".
May I know the reason or how can i achieve my goal? Many thanks.
select (select count(*) from table1) as count1, (select count(*) from table2) as count2;
What are you doing with a cursor ? How are you getting it ? (content resolver, exec raw sql, etc etc).
There are more correct ways to do a select count, as the related links clearly show.
So normally use two queries
String[] queries = {"select count(*) from table1",
"select count(*) from table2"};
Then use Cursor and perform query and getter for get value.
Cursor c = null;
int index = 0;
int totalCount = 0;
while (index < queries.length) {
c = db.rawQuery(queries[index], null);
if (c.moveToFirst()) {
totalCount += c.getInt(0);
}
index++;
}

counting total rows in sql lite

I wrote a method in my database manager that is suppose to return the total amount of rows in a table called homeIcons; but i noticed that it returns 0 when there are 0, 1 there is 1, and then 10 when there are 3? so something is wrong with my method.. please see below:
public int getHomeScreenTotal (){
SQLiteDatabase db=this.getReadableDatabase();
Cursor c = db.rawQuery("select count(*) as count from "+ homeIcons,null);
c.moveToFirst();
int total = c.getInt(0);
return total;
}
EDIT
so i edited my code.. and i have rewritten this method in just about every way possible.. The problem is not that it isn't returning the right amount of rows, because it is.. it is just that it is returning the number in binary.. instead of 3, it returns 11 instead of 5 it returns 101 .. UHG!!!! i just want an int! I can't tell if this is a bug in the adroid/java method for accessing a SQLite DB or if i am missing something.. I have even tried duck punching it to an int, but to no avail.. :(
EDIT
ok i just tried to force the binary to an int using the following method:
public int getHomeScreenTotal (){
SQLiteDatabase db=this.getReadableDatabase();
int rows;
String bin = ""+ db.compileStatement("SELECT COUNT(*) FROM " + homeIcons).simpleQueryForLong();
rows = Integer.parseInt(bin, 2);
return rows;
}
this throws an Error of
java.lang.NumberFormatException: Invalid int: "7"
where the "7" is, is actually the number it is suppose to return.. if i have 5 rows i get an error of Invalid int "5"; ect..
You'll be much happier making the database do the lifting for you.
String query = "select count(*) from " + homeIcons;
you can get the number of rows from SQLite by executing the following query:
SELECT count(*) as count FROM homeIcons;
it will return a table containing one row, which contains only the number of rows in your homeIcons table:
+---------+
| count |
+---------+
| ### |
+---------+
To use this code in your application, execute:
Cursor c = db.rawQuery("SELECT count(*) AS count FROM "+ homeIcons,null);
c.moveToFirst();
int total = c.getInt(0);
EDIT
to get the decimal number out of the binary that is returned, use:
String bin = "" + c.getInt(0);
int total = Integer.parseInt(bin, 2);

Categories

Resources