searching a particular string in the entire database using Sqlite3? - android

I want to search a particular string in the whole database table and get the row details of the matched column. For example I am having the table as like below
**name email address designation**
sai xy#mail 75385 nagar
thiru y#mail 75893 city
Now I am having the searching key like "nagar" or "thiru" how can prepare a query for it. if any one knows Please help me. Thanks in advance.

Read the whole table into a cursor and search in each column to get column name.
May be like this:
private String getColumnName(String key){
String columnName="";
DataBaseAdapter dba=new DatabaseAdapter(getApplicationContext());
dba.open();
Cursor cr=dba.fetchAllData();
cr.moveToFirst();
while(!cr.isAfterLast()){
if(key.equals(cr.getString(cr.getColumnIndex("name")))){
columnName="name";
}
cr.moveToNext();
}
cr.moveToFirst();
while(!cr.isAfterLast()){
if(key.equals(cr.getString(cr.getColumnIndex("email")))){
columnName="email";
}
cr.moveToNext();
}
cr.moveToFirst();
while(!cr.isAfterLast()){
if(key.equals(cr.getString(cr.getColumnIndex("address")))){
columnName="address";
}
cr.moveToNext();
}
cr.moveToFirst();
while(!cr.isAfterLast()){
if(key.equals(cr.getString(cr.getColumnIndex("designation")))){
columnName="designation";
}
cr.moveToNext();
}
return columnName;
}
fetchAllData() function in DataBaseAdapter class contains following code:
public Cursor fetchAllData(){
try {
return database.query(TABLENAME, null, null, null, null,
null, null);
} catch (Exception e) {
return null;
}
}
This will give column name of your key.
So now it's easy to run query like this:
String query= "SELECT * FROM tablename where "+getColumnName()+"='"+key+"'" ;

try this query..
SELECT * FROM tablename WHERE name = 'nagar' or email = 'nagar' or address = 'nagar' or designation = 'nagar';
or
SELECT * FROM tablename WHERE name or email or address or designation = 'nagar';

Related

Sepecific data from table

I have a table and I want to get a specific item from it.
For example the statement :
"SELECT password FROM "+tableName+" WHERE username='"+username+"'";
How can I use that statement and get the string value of the password I asked for?
(I was able to get the curser but I couldn't get from it the string value of it)
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = null;
String sql ="SELECT password FROM "+tableName+" WHERE username='"+username+"'";
cursor= db.rawQuery(sql,null);
String checked = cursor.getString(3);
if(checked.equals(password)){
return true;
}else{
return false;
}
The problam is with the line:
String checked = cursor.getString(3);
Any suggestions?
I suggest to use this
cursor.getString(cursor.getColumnIndex("column name"));
Best regards

How to check the value already excists or not in sqlite db in android?

In my application I am saving a bill number in SQLite database. Before I add a new bill number how to check if the bill number exists in the DB.
My main class code is,
String bill_no_excist_or_not = db.billno_exist_or_not(""+et_bill_number.getText().toString());
Log.v("Bill No", ""+bill_no_excist_or_not);
My DB Code,
String billno_exist_or_not(String bill_number){
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_BILL_DETAILS, new String[] { KEY_BILL_NUMBER }, KEY_BILL_NUMBER + "=?"
+ new String[] { bill_number }, null, null, null, null);
//after this i don't know how to return the values
return bill_number;
}
I don't know how to check the values which is already available or not in DB. Can any one know please help me to solve this problem.
Here is the function that helps you to find whether the value is available in database or not.
Here please replace your query with my query..
public int isUserAvailable(int userId)
{
int number = 0;
Cursor c = null;
try
{
c = db.rawQuery("select user_id from user_table where user_id = ?", new String[] {String.valueOf(userId)});
if(c.getCount() != 0)
number = c.getCount();
}
catch(Exception e) {
e.printStackTrace();
} finally {
if(c!=null) c.close();
}
return number;
}
Make your KEY_BILL_NUMBER column in your table UNIQUE and you can just insert using insertWithOnConflict with the flag SQLiteDatabase.CONFLICT_IGNORE

Concat database tables 1 field multiple records string in one row

I have a tables and records like :
EmployeeName
------------
Ram
Laxman
Bharat
Shatrugn
where i want to output to concat all values in one row in a single query:
I want result like:
Ram,Laxman,bharat,shatrugn
Concat string with ,(comma) in singlee line..
but i don't know that how to concat in android using cursor...
In SQLite, you can use GROUP_CONCAT():
select Group_Concat(EmployeeName)
from table1
See SQL Fiddle with Demo
If you had multiple fields that you want to return, then you would use a GROUP BY with the query, similar to this:
select id, Group_Concat(EmployeeName)
from table1
group by id
See SQL Fiddle with Demo
Here is my code i used...hope it helps you.
private SQLiteDatabase myDataBase;
Cursor cursor;
String S="";
String myPath2 = yourDBpath + yourDBNAME;
try{
myDataBase = SQLiteDatabase.openDatabase(myPath2, null,SQLiteDatabase.OPEN_READWRITE);
String sql="your query";
cursor=myDataBase.rawQuery(sql, null);
if(cursor != null)
{
while(cursor.moveToNext())
{
S=S.append(cursor.getString(0));
}
}
}
}catch(Exception e){
}finally{
myDataBase.close();
}
Final result will be there in String S.
String values;
if (cursor.moveToFirst()) {
do {
values=values + cursor.getString(0)+",";
} while (cursor.moveToNext());
remove last comma
if (values.length() > 0)
{
values= values.substring(0,values.length() - 1);
}

How to set the arraylist item to be add in to reverse order?

In My Application, I am going to store name of all the available tables from my database with this code:
public ArrayList<Object> showAllTable()
{
ArrayList<Object> tableList = new ArrayList<Object>();
String SQL_GET_ALL_TABLES = "SELECT name FROM sqlite_master WHERE type='table'";
Cursor cursor = db.rawQuery(SQL_GET_ALL_TABLES, null);
cursor.moveToFirst();
if (!cursor.isAfterLast())
{
do
{
if(cursor.getString(0).equals("android_metadata"))
{
//System.out.println("Get Metadata");
continue;
}
else
{
tableList.add(cursor.getString(0));
}
}
while (cursor.moveToNext());
}
cursor.close();
return tableList;
}
Yes i am able to store it. But while i am going to display it in to ListView, it will display in such way that last created shown at last. I want to display the list of the table as Last created, display first in to ListView.
Please help me, What should I have to do in my code to set such way of displaying tables?
There are several ways to do it. The easiest is probably to change your SQL call by adding ORDER BY. Here's something you can try out:
To order the items ascending:
String SQL_GET_ALL_TABLES = "SELECT name FROM sqlite_master WHERE type='table' ORDER BY name ASC";
Or descending:
String SQL_GET_ALL_TABLES = "SELECT name FROM sqlite_master WHERE type='table' ORDER BY name DESC";
Alternative solution
Another option would be to do it like you're doing it right now, and instead go through the Cursor from the last to the first item. Here's some pseudo code:
if (cursor.moveToLast()) {
while (cursor.moveToPrevious()) {
// Add the Cursor data to your ArrayList
}
}
before return the values just call the method
Collections.reverse(tableList);
see the full code
public ArrayList<Object> showAllTable()
{
ArrayList tableList = new ArrayList();
String SQL_GET_ALL_TABLES = "SELECT name FROM sqlite_master WHERE type='table'";
Cursor cursor = db.rawQuery(SQL_GET_ALL_TABLES, null);
cursor.moveToFirst();
if (!cursor.isAfterLast())
{
do
{
if(cursor.getString(0).equals("android_metadata"))
{
//System.out.println("Get Metadata");
continue;
}
else
{
tableList.add(cursor.getString(0));
}
}
while (cursor.moveToNext());
}
cursor.close();
Collections.reverse(tableList);
return tableList;
}

Android get list of tables

Does anyone know the SQL to get a list of table names via code in Android? I know .tables does it through command shell but this doesn't work through code. Is it anything to do with the meta-data, etc.?
Just had to do the same. This seems to work:
public ArrayList<Object> listTables()
{
ArrayList<Object> tableList = new ArrayList<Object>();
String SQL_GET_ALL_TABLES = "SELECT name FROM " +
"sqlite_master WHERE type='table' ORDER BY name";
Cursor cursor = db.rawQuery(SQL_GET_ALL_TABLES, null);
cursor.moveToFirst();
if (!cursor.isAfterLast()) {
do {
tableList.add(cursor.getString(0));
}
while (cursor.moveToNext());
}
cursor.close();
return tableList;
}
Got it:
SELECT * FROM sqlite_master WHERE type='table'

Categories

Resources